/*
 *   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.schematicsystem.commands.schematiccommand.parts;

import com.sk89q.worldedit.*;
import com.sk89q.worldedit.bukkit.BukkitPlayer;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.session.ClipboardHolder;
import de.steamwar.command.AbstractSWCommand;
import de.steamwar.command.SWCommand;
import de.steamwar.linkage.Linked;
import de.steamwar.schematicsystem.SchematicSystem;
import de.steamwar.schematicsystem.autocheck.AutoChecker;
import de.steamwar.schematicsystem.autocheck.AutoCheckerResult;
import de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommand;
import de.steamwar.sql.GameModeConfig;
import de.steamwar.sql.SchematicData;
import de.steamwar.sql.SchematicNode;
import org.bukkit.Material;
import org.bukkit.entity.Player;

import java.io.IOException;
import java.util.logging.Level;

import static de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommandUtils.check;

@AbstractSWCommand.PartOf(SchematicCommand.class)
@Linked
public class CheckPart extends SWCommand {
    public CheckPart() {
        super(null);
    }

    @Register("check")
    public void checkCommand(Player player, @Validator("isOwnerSchematicValidator") SchematicNode node, GameModeConfig<Material, String> type) {
        try {
            check(player, new SchematicData(node).load(), type, node.getName(), false);
        } catch (IOException e) {
            SchematicSystem.MESSAGE.send("UTIL_LOAD_ERROR", player);
        }
    }

    @Register(value = {"check", "clipboard"})
    public void checkClipboardCommand(Player player, @ErrorMessage("UTIL_CHECK_TYPE_NOT_FOUND") GameModeConfig<Material, String> type) {
        try {
            check(player, WorldEdit.getInstance().getSessionManager().findByName(player.getName()).getClipboard().getClipboard(), type, "clipboard", false);
        } catch (EmptyClipboardException e) {
            SchematicSystem.MESSAGE.send("COMMAND_CHECK_CLIPBOARD_EMPTY", player);
        }
    }

    @Register(value = {"check", "selection"})
    public void checkSelectionCommand(Player player, @ErrorMessage("UTIL_CHECK_TYPE_NOT_FOUND") GameModeConfig<Material, String> type) {
        try {
            Clipboard clipboard = new BlockArrayClipboard(WorldEdit.getInstance().getSessionManager().findByName(player.getName()).getSelection(new BukkitWorld(player.getWorld())));
            EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(new BukkitWorld(player.getWorld()), -1);

            SchematicCommand.createCopy(editSession, clipboard);

            check(player, clipboard, type, "selection", false);
        } catch (IncompleteRegionException e) {
            SchematicSystem.MESSAGE.send("COMMAND_CHECK_SELECTION_INCOMPLETE", player);
        } catch (WorldEditException e) {
            SchematicSystem.MESSAGE.send("COMMAND_SAVE_ERROR", player);
        }
    }

    @Register("fix")
    public void fixSchematicCommand(Player player, @ErrorMessage("UTIL_CHECK_TYPE_NOT_FOUND") GameModeConfig<Material, String> type) {
        Clipboard clipboard;
        try {
            clipboard = WorldEdit.getInstance().getSessionManager().findByName(player.getName()).getClipboard().getClipboard();
        } catch (EmptyClipboardException e) {
            SchematicSystem.MESSAGE.send("COMMAND_CHECK_CLIPBOARD_EMPTY", player);
            return;
        }
        AutoCheckerResult result = AutoChecker.impl.check(clipboard, type);
        if (result.isOk()) {
            SchematicSystem.MESSAGE.send("COMMAND_FIX_OK", player);
            return;
        }
        try {
            clipboard = SchematicCommand.fixClipboard(clipboard, result, type);
            WorldEdit.getInstance().getSessionManager().get(new BukkitPlayer(player)).setClipboard(new ClipboardHolder(clipboard));
            AutoCheckerResult after = AutoChecker.impl.check(clipboard, type);
            if (after.isOk()) {
                SchematicSystem.MESSAGE.send("COMMAND_FIX_DONE", player);
            } else {
                after.sendErrorMessage(player, SchematicSystem.MESSAGE.parse("COMMAND_FIX_MANUAL", player));
                SchematicSystem.MESSAGE.send("COMMAND_FIX_COULD_NOT_FIX", player);
            }
        } catch (Exception e) {
            SchematicSystem.MESSAGE.send("COMMAND_FIX_ERROR", player);
            SchematicSystem.getInstance().getLogger().log(Level.SEVERE, e.getMessage(), e);
        }
    }
}
