/*
 *   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;

import de.steamwar.command.SWCommand;
import de.steamwar.linkage.Linked;
import de.steamwar.schematicsystem.SchematicSystem;
import de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommandUtils;
import de.steamwar.sql.*;
import org.bukkit.entity.Player;

import java.io.IOException;

@Linked
public class DownloadCommand extends SWCommand {
    public DownloadCommand() {
        super("download", "/download");
    }

    @Register(help = true)
    public void genericCommand(Player player, String... args) {
        SteamwarUser user = SteamwarUser.get(player.getUniqueId());
        SchematicNode copyNode = SchematicNode.getSchematicNode(user.getId(), "//copy", (Integer) null);
        boolean newSchem = false;
        if (copyNode == null) {
            copyNode = SchematicNode.createSchematicNode(user.getId(), "//copy", null, SchematicType.Normal.toDB(), "");
            newSchem = true;
        }

        try {
            SchematicData.saveFromPlayer(player, copyNode);
        } catch (IOException e) {
            SchematicSystem.MESSAGE.send("DOWNLOAD_ERROR", player);
            if (newSchem) {
                copyNode.delete();
            }
            throw new SecurityException(e);
        } catch (NoClipboardException e) {
            SchematicSystem.MESSAGE.send("COMMAND_SAVE_CLIPBOARD_EMPTY", player);
            if (newSchem) {
                copyNode.delete();
            }
            return;
        }

        SchematicCommandUtils.download(player, copyNode);
    }
}
