/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.bausystem.features.backup;

import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.region.Region;
import de.steamwar.bausystem.region.RegionBackups;
import de.steamwar.bausystem.region.flags.ChangedMode;
import de.steamwar.bausystem.region.flags.Flag;
import de.steamwar.command.PreviousArguments;
import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper;
import de.steamwar.inventory.SWItem;
import de.steamwar.inventory.SWListInv;
import de.steamwar.linkage.Linked;
import net.md_5.bungee.api.chat.ClickEvent;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.*;
import java.util.stream.Collectors;

@Linked
public class BackupCommand extends SWCommand {

    public BackupCommand() {
        super("backup", "bu");
    }

    static boolean checkGlobalRegion(Region region, Player p) {
        if (region.getType().isGlobal()) {
            BauSystem.MESSAGE.send("BACKUP_REGION_NO_REGION", p);
            return true;
        }
        return false;
    }

    @Register(value = "create", description = "BACKUP_HELP_CREATE")
    public void backupCreate(@Validator("owner") Player p) {
        Region region = Region.getRegion(p.getLocation());
        if (checkGlobalRegion(region, p)) {
            return;
        }
        if (region.getRegionData().get(Flag.CHANGED).isWithDefault(ChangedMode.NO_CHANGE)) {
            BauSystem.MESSAGE.send("BACKUP_CREATE_NO_CHANGE", p);
            return;
        }
        Optional<RegionBackups.Backup> backup = region.getBackups().create(RegionBackups.BackupType.MANUAL);
        if (backup.isPresent()) {
            BauSystem.MESSAGE.send("BACKUP_CREATE_SUCCESS", p);
        } else {
            BauSystem.MESSAGE.send("BACKUP_CREATE_FAILURE", p);
        }
    }

    @Register(value = "load", description = "BACKUP_HELP_LOAD")
    public void backupLoad(@Validator("owner") Player p, @Mapper("backup") @ErrorMessage("BACKUP_LOAD_FAILURE") RegionBackups.Backup backup) {
        if (backup.load()) {
            BauSystem.MESSAGE.send("BACKUP_LOAD", p);
        } else {
            BauSystem.MESSAGE.send("BACKUP_LOAD_FAILURE", p);
        }
    }

    @Register(value = "list", description = "BACKUP_HELP_LIST")
    public void backupList(Player p) {
        Region region = Region.getRegion(p.getLocation());
        if (checkGlobalRegion(region, p)) {
            return;
        }
        List<RegionBackups.Backup> backups = listBackup(p);
        BauSystem.MESSAGE.send("BACKUP_LIST_HEAD", p, backups.size());
        backups.forEach(backup -> {
            BauSystem.MESSAGE.send("BACKUP_LIST_ENTRY", p, "/backup load " + backup.getName(), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/backup load " + backup.getName()), backup.getName());
        });
    }

    @Register(value = "gui", description = "BACKUP_HELP_GUI")
    public void backupGui(Player p) {
        Region region = Region.getRegion(p.getLocation());
        if (checkGlobalRegion(region, p)) {
            return;
        }
        List<RegionBackups.Backup> backups = listBackup(p);
        List<SWListInv.SWListEntry<RegionBackups.Backup>> swListEntries = new ArrayList<>();
        List<String> lore = Arrays.asList(BauSystem.MESSAGE.parse("BACKUP_LORE", p));
        for (int i = 0; i < backups.size(); i++) {
            RegionBackups.Backup backup = backups.get(i);
            SWItem swItem = new SWItem(Material.BRICK, BauSystem.MESSAGE.parse("BACKUP_ITEM_NAME", p, backup.getName()), lore, false, clickType -> {
            });
            swItem.getItemStack().setAmount(i + 1);
            swListEntries.add(new SWListInv.SWListEntry<>(swItem, backup));
        }
        SWListInv<RegionBackups.Backup> swListInv = new SWListInv<>(p, BauSystem.MESSAGE.parse("BACKUP_INV_NAME", p), swListEntries, (clickType, s) -> {
            p.getOpenInventory().close();
            backupLoad(p, s);
        });
        swListInv.open();
    }

    @Mapper(value = "backup", local = true)
    public TypeMapper<RegionBackups.Backup> backupMapper() {
        return new TypeMapper<>() {
            @Override
            public RegionBackups.Backup map(CommandSender commandSender, String[] previousArguments, String s) {
                return Region.getRegion(((Player) commandSender).getLocation()).getBackups().get(s);
            }

            @Override
            public Collection<String> tabCompletes(CommandSender sender, PreviousArguments previousArguments, String s) {
                return listBackup((Player) sender).stream().map(RegionBackups.Backup::getName).collect(Collectors.toList());
            }
        };
    }

    private List<RegionBackups.Backup> listBackup(Player p) {
        Region region = Region.getRegion(p.getLocation());
        if (checkGlobalRegion(region, p)) {
            return Collections.emptyList();
        }
        try {
            return region.getBackups().list();
        } catch (NullPointerException e) {
            return Collections.emptyList();
        }
    }
}
