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

import com.sk89q.worldedit.extent.clipboard.Clipboard;
import de.steamwar.core.WorldEditWrapper;
import org.bukkit.entity.Player;

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class SchematicData {

    private final NodeData data;

    public SchematicData(SchematicNode node) {
        this.data = NodeData.getLatest(node);
        if (node.isDir()) throw new SecurityException("Node is Directory");
    }

    public SchematicData(SchematicNode node, int revision) {
        if (node.isDir()) throw new SecurityException("Node is Directory");

        if (revision < 1) {
            this.data = NodeData.getLatest(node);
        } else {
            if (NodeData.getRevisions(node) < revision) {
                throw new IllegalArgumentException("Revision " + revision + " does not exist");
            }
            this.data = NodeData.get(node, revision);
        }
    }

    public Clipboard load() throws IOException, NoClipboardException {
        return WorldEditWrapper.impl.getClipboard(data);
    }

    public void loadToPlayer(Player player) throws IOException, NoClipboardException {
        WorldEditWrapper.impl.setPlayerClipboard(player, WorldEditWrapper.impl.getClipboard(data));
    }

    public static void saveFromPlayer(Player player, SchematicNode node) throws IOException, NoClipboardException {
        NodeData.saveFromStream(node, WorldEditWrapper.impl.getPlayerClipboard(player), WorldEditWrapper.impl.getNativeFormat());
    }

    @Deprecated
    public static void saveFromBytes(SchematicNode node, byte[] bytes, NodeData.SchematicFormat newFormat) {
        NodeData.saveFromStream(node, new ByteArrayInputStream(bytes), newFormat);
    }
}
