/*
 * This file is a part of the SteamWar software.
 *
 * Copyright (C) 2021  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 com.sk89q.worldedit.EditSession;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.region.Color;
import de.steamwar.bausystem.region.Region;
import de.steamwar.bausystem.region.flags.Flag;
import de.steamwar.bausystem.region.flags.flagvalues.ColorMode;
import de.steamwar.bausystem.region.tags.Tag;
import de.steamwar.bausystem.utils.PasteBuilder;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import de.steamwar.command.TypeValidator;
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.entity.Player;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
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.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.get(Tag.CHANGED)) {
            BauSystem.MESSAGE.send("BACKUP_CREATE_NO_CHANGE", p);
            return;
        }
        if (region.backup()) {
            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("backupName") String backupName) {
        Region region = Region.getRegion(p.getLocation());
        if (checkGlobalRegion(region, p)) {
            return;
        }

        File backupFile = region.getBackupFile(backupName.replace('_', ' '));
        if (backupFile == null) {
            BauSystem.MESSAGE.send("BACKUP_LOAD_FAILURE", p);
            return;
        }
        EditSession editSession = new PasteBuilder(new PasteBuilder.FileProvider(backupFile))
                .pastePoint(region.getMinPoint().add(region.getPrototype().getSizeX() / 2, 0, region.getPrototype().getSizeZ() / 2))
                .minPoint(region.getMinPoint())
                .maxPoint(region.getMaxPoint())
                .waterLevel(region.getWaterLevel())
                .run();
        region.remember(editSession);
        BauSystem.MESSAGE.send("BACKUP_LOAD", 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<String> backups = listBackup(p);
        BauSystem.MESSAGE.send("BACKUP_LIST_HEAD", p, backups.size());
        backups.forEach(s -> {
            BauSystem.MESSAGE.send("BACKUP_LIST_ENTRY", p, "/backup load " + s, new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/backup load " + s), s);
        });
    }

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

    @Mapper(value = "backupName", local = true)
    public TypeMapper<String> backupMapper() {
        return SWCommandUtils.createMapper(s -> s, (commandSender, s) -> listBackup((Player) commandSender));
    }

    private List<String> listBackup(Player p) {
        Region region = Region.getRegion(p.getLocation());
        if (checkGlobalRegion(region, p)) {
            return Collections.emptyList();
        }
        try {
            return region.listBackup().stream().map(s -> s.substring(0, s.length() - 6).replace(' ', '_')).collect(Collectors.toList());
        } catch (NullPointerException e) {
            return Collections.emptyList();
        }
    }
}
