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

import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter;
import com.sk89q.worldedit.function.operation.ForwardExtentCopy;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.math.transform.AffineTransform;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockTypes;
import de.steamwar.fightsystem.Config;
import de.steamwar.fightsystem.FightSystem;
import de.steamwar.sql.NodeData;
import de.steamwar.sql.SchematicData;
import de.steamwar.sql.SchematicNode;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.util.Vector;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class WorldeditWrapper {
    public static final WorldeditWrapper impl = new WorldeditWrapper();

    private static final Map<BaseBlock, String> colorBlocks = new HashMap<>();

    static {
        colorBlocks.put(Objects.requireNonNull(BlockTypes.PINK_WOOL).getDefaultState().toBaseBlock(), "_wool");
        colorBlocks.put(Objects.requireNonNull(BlockTypes.PINK_TERRACOTTA).getDefaultState().toBaseBlock(), "_terracotta");
        colorBlocks.put(Objects.requireNonNull(BlockTypes.PINK_STAINED_GLASS).getDefaultState().toBaseBlock(), "_stained_glass");
        colorBlocks.put(Objects.requireNonNull(BlockTypes.PINK_STAINED_GLASS_PANE).getDefaultState().toBaseBlock(), "_stained_glass_pane");
        colorBlocks.put(Objects.requireNonNull(BlockTypes.PINK_CONCRETE).getDefaultState().toBaseBlock(), "_concrete");
        colorBlocks.put(Objects.requireNonNull(BlockTypes.PINK_CONCRETE_POWDER).getDefaultState().toBaseBlock(), "_concrete_powder");
        colorBlocks.put(Objects.requireNonNull(BlockTypes.PINK_CARPET).getDefaultState().toBaseBlock(), "_carpet");
    }

    public void replaceTeamColor(Clipboard clipboard, DyeColor c) throws WorldEditException {
        BlockVector3 minimum = clipboard.getRegion().getMinimumPoint();
        Map<BaseBlock, BaseBlock> replaceMap = new HashMap<>();
        colorBlocks.forEach((base, postfix) -> replaceMap.put(base, Objects.requireNonNull(BlockTypes.get(c.name().toLowerCase() + postfix)).getDefaultState().toBaseBlock()));

        for (int x = 0; x < clipboard.getDimensions().x(); x++) {
            for (int y = 0; y < clipboard.getDimensions().y(); y++) {
                for (int z = 0; z < clipboard.getDimensions().z(); z++) {
                    BlockVector3 pos = minimum.add(x, y, z);
                    BaseBlock replacement = replaceMap.get(clipboard.getFullBlock(pos));
                    if (replacement != null) clipboard.setBlock(pos, replacement);
                }
            }
        }
    }

    public int getWaterDepth(Clipboard clipboard) {
        BlockVector3 it = clipboard.getMinimumPoint().add(0, 0, 1);
        int depth = 0;
        while (!clipboard.getBlock(it).getBlockType().getMaterial().isAir()) {
            depth++;
            it = it.add(0, 1, 0);
        }
        return depth;
    }

    public void pasteClipboard(Clipboard clipboard, Location position, Vector offset, AffineTransform aT) {
        EditSession e = WorldEdit.getInstance().getEditSessionFactory().getEditSession(new BukkitWorld(position.getWorld()), -1);
        ClipboardHolder ch = new ClipboardHolder(clipboard);
        ch.setTransform(aT);
        Operations.completeBlindly(ch.createPaste(e).to(BukkitAdapter.asVector(position).add(
                aT.apply(Vector3.at(offset.getX(), offset.getY(), offset.getZ()).add(clipboard.getOrigin().toVector3()).subtract(clipboard.getMinimumPoint().toVector3()))
        ).toBlockPoint()).build());
        e.flushSession();
    }

    public Vector getDimensions(Clipboard clipboard) {
        BlockVector3 dims = clipboard.getDimensions();
        return new Vector(dims.x(), dims.y(), dims.z());
    }

    public Clipboard loadChar(String charName) throws IOException {
        File file = new File(FightSystem.getPlugin().getDataFolder(), "text/" + charName + ".schem");
        Clipboard clipboard;
        try (ClipboardReader reader = Objects.requireNonNull(ClipboardFormats.findByFile(file)).getReader(new FileInputStream(file))) {
            clipboard = reader.read();
        }
        return clipboard;
    }

    public void saveSchem(SchematicNode schem, Region region, int minY) throws WorldEditException {
        World w = new BukkitWorld(Config.world);
        BlockVector3 min = BlockVector3.at(region.getMinX(), minY, region.getMinZ());
        CuboidRegion cuboidRegion = new CuboidRegion(w, min, BlockVector3.at(region.getMaxX(), region.getMaxY(), region.getMaxZ()).subtract(BlockVector3.ONE));
        BlockArrayClipboard clipboard = new BlockArrayClipboard(cuboidRegion);

        ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy(
                WorldEdit.getInstance().getEditSessionFactory().getEditSession(w, -1), cuboidRegion, clipboard, min
        );
        forwardExtentCopy.setCopyingEntities(false);
        Operations.complete(forwardExtentCopy);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ClipboardWriter writer = BuiltInClipboardFormat.SPONGE_SCHEMATIC.getWriter(outputStream);
            writer.write(clipboard);
            writer.close();
        } catch (IOException e) {
            throw new SecurityException(e);
        }

        SchematicData.saveFromBytes(schem, outputStream.toByteArray(), NodeData.SchematicFormat.SPONGE_V2);
    }
}
