/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2024 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.core;

import com.fastasyncworldedit.core.extent.clipboard.io.FastSchematicReaderV2;
import com.fastasyncworldedit.core.extent.clipboard.io.FastSchematicReaderV3;
import com.fastasyncworldedit.core.extent.clipboard.io.FastSchematicWriterV3;
import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.NBTOutputStream;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.MCEditSchematicReader;
import com.sk89q.worldedit.extent.clipboard.io.sponge.SpongeSchematicV1Reader;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.math.transform.Transform;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.session.ClipboardHolder;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import org.enginehub.linbus.stream.LinBinaryIO;
import org.enginehub.linbus.stream.LinStream;
import org.enginehub.linbus.tree.LinCompoundTag;
import org.enginehub.linbus.tree.LinRootEntry;
import org.enginehub.linbus.tree.LinTagType;

import java.io.*;

public class WorldEditWrapper21 implements WorldEditWrapper {

    @Override
    public InputStream getPlayerClipboard(Player player, boolean schemFormat) {
        return WorldEditWrapper.getPlayerClipboard(player, schemFormat, (outputStream, clipboard, clipboardHolder) -> {
            try {
                new FastSchematicWriterV3(new NBTOutputStream(outputStream)).write(clipboard);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void setPlayerClipboard(Player player, InputStream is, boolean schemFormat) {
        Clipboard clipboard = null;
        try {
            clipboard = getClipboard(is, schemFormat);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        if (clipboard == null)
            throw new SecurityException("Clipboard is null");

        Actor actor = WorldEditWrapper.getWorldEditPlugin().wrapCommandSender(player);
        WorldEditWrapper.getWorldEditPlugin().getWorldEdit().getSessionManager().get(actor).setClipboard(new ClipboardHolder(clipboard));
    }

    @Override
    public Clipboard getClipboard(InputStream is, boolean schemFormat) throws IOException {
        if (!schemFormat) {
            return new MCEditSchematicReader(new NBTInputStream(is)).read();
        } else {
            BufferedInputStream bis = new BufferedInputStream(is);

            bis.mark(Integer.MAX_VALUE);

            LinStream linStream = LinBinaryIO.read(new DataInputStream(bis));

            LinCompoundTag entry = LinRootEntry.readFrom(linStream).value();

            bis.reset();

            switch (entry.getTag("Version", LinTagType.intTag()).valueAsInt()) {
                case 1:
                    return new SpongeSchematicV1Reader(entry.linStream()).read();
                case 2:
                    return new FastSchematicReaderV2(new NBTInputStream(bis)).read();
                case 3:
                    return new FastSchematicReaderV3(bis).read();
                default:
                    throw new IOException("Unknown schematic version");
            }
        }
    }

    @Override
    public org.bukkit.util.Vector getOrigin(Clipboard clipboard) {
        return new org.bukkit.util.Vector(clipboard.getOrigin().x(), clipboard.getOrigin().y(), clipboard.getOrigin().z());
    }

    @Override
    public Vector getMinimum(Region region) {
        return new Vector(region.getMinimumPoint().x(), region.getMinimumPoint().y(), region.getMinimumPoint().z());
    }

    @Override
    public Vector getMaximum(Region region) {
        return new Vector(region.getMaximumPoint().x(), region.getMaximumPoint().y(), region.getMaximumPoint().z());
    }

    @Override
    public Vector applyTransform(Vector vector, Transform transform) {
        Vector3 v = Vector3.at(vector.getX(), vector.getY(), vector.getZ());
        v = transform.apply(v);
        return new org.bukkit.util.Vector(v.x(), v.y(), v.z());
    }
}
