/*
 *   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 de.steamwar.command.AbstractSWCommand;
import de.steamwar.command.SWCommand;
import de.steamwar.inventory.SWAnvilInv;
import de.steamwar.inventory.SchematicSelector;
import de.steamwar.linkage.Linked;
import de.steamwar.providers.BauServerInfo;
import de.steamwar.schematicsystem.SchematicSystem;
import de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommand;
import de.steamwar.sql.*;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;

import java.util.logging.Level;

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

@AbstractSWCommand.PartOf(SchematicCommand.class)
@Linked
public class SavePart extends SWCommand {

    public SavePart() {
        super(null);
    }

    @Register("save")
    public void saveSchem(Player player) {
        SchematicSelector selector = new SchematicSelector(player, SchematicSelector.selectSchematicNode(), schematicNode -> {
            if (schematicNode == null || schematicNode.isDir()) {
                SWAnvilInv anvilInv = new SWAnvilInv(player, SchematicSystem.MESSAGE.parse("COMMAND_ENTER_NAME", player));
                anvilInv.setCallback(s -> saveSchem(player, schematicNode == null ? s : (schematicNode.generateBreadcrumbs(getUser(player)) + s)));
                anvilInv.setItem(Material.CAULDRON);
                anvilInv.open();
            } else {
                saveSchem(player, schematicNode.generateBreadcrumbs(getUser(player)));
            }
        });
        selector.setSingleDirOpen(false);
        selector.open();
    }

    @Register("save")
    public void saveSchem(Player player, @AbstractSWCommand.Mapper("stringMapper") String name) {
        SteamwarUser user = getUser(player);
        if (BauServerInfo.isBauServer() && BauServerInfo.getOwnerId() != user.getId() &&
                (Punishment.isPunished(user, Punishment.PunishmentType.NoSchemReceiving, punishment ->
                        SchematicSystem.MESSAGE.send("COMMAND_PUNISHMENT_NO_SAVE_EXTERNAL", player)) ||
                        Punishment.isPunished(SteamwarUser.byId(BauServerInfo.getOwnerId()), Punishment.PunishmentType.NoSchemSharing, punishment ->
                                SchematicSystem.MESSAGE.send("COMMAND_PUNISHMENT_NO_SAVE", player)))) {
            return;
        }
        if (name.endsWith("/")) {
            SchematicSystem.MESSAGE.send("COMMAND_SAVE_NO_NAME", player);
            return;
        }
        if (name.startsWith("/")) name = name.substring(1);
        String[] layers = name.split("/");
        if (invalidSchemName(player, layers)) return;
        SchematicNode currentNode = mkdirs(layers, user, 1);

        SchematicNode node = SchematicNode.getNodeFromPath(user, String.join("/", layers));
        if (node != null) {
            if (node.isDir()) {
                SchematicSystem.MESSAGE.send("COMMAND_SAVE_FOLDER", player);
                return;
            } else if (!node.getSchemtype().writeable() || node.getOwner() != user.getId()) {
                SchematicSystem.MESSAGE.send("COMMAND_SAVE_NO_OVERWRITE", player);
                return;
            }
        }

        boolean newSchem = false;
        if (node == null) {
            newSchem = true;
            node = SchematicNode.createSchematic(user.getId(), layers[layers.length - 1], currentNode == null ? 0 : currentNode.getId());
        }

        try {
            SchematicData.saveFromPlayer(player, node);
        } catch (NoClipboardException e) {
            SchematicSystem.MESSAGE.send("COMMAND_SAVE_CLIPBOARD_EMPTY", player);
            if (newSchem) node.delete();
            return;
        } catch (Exception ex) {
            Bukkit.getLogger().log(Level.SEVERE, "Could not save schematic", ex);
            SchematicSystem.MESSAGE.send("COMMAND_SAVE_ERROR", player);
            if (newSchem) node.delete();
            return;
        }

        SchematicSystem.MESSAGE.send(newSchem ? "COMMAND_SAVE_DONE" : "COMMAND_SAVE_OVERWRITE", player, node.generateBreadcrumbs(user));
    }

    @Register("dir")
    @Register("ordner")
    @Register("mkdir")
    public void mkdir(Player player, @Mapper("dirStringMapper") String name) {
        SteamwarUser user = getUser(player);
        if (name.startsWith("/")) name = name.substring(1);
        if (name.endsWith("/")) name = name.substring(0, name.length() - 1);
        String[] layers = name.split("/");
        if (invalidSchemName(player, layers)) return;
        SchematicNode node = mkdirs(layers, user, 0);
        SchematicSystem.MESSAGE.send("COMMAND_DIR_DONE", player, node.generateBreadcrumbs(user));
    }
}
