/*
    This file is a part of the SteamWar software.

    Copyright (C) 2021  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.jnbt.NBTInputStream;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock;
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.ClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter;
import com.sk89q.worldedit.extent.clipboard.io.SchematicReader;
import com.sk89q.worldedit.function.operation.ForwardExtentCopy;
import com.sk89q.worldedit.function.operation.Operations;
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 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.Material;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

@SuppressWarnings("deprecation")
public class WorldeditWrapper8 implements WorldeditWrapper {

    protected static final int COLOR_TO_REPLACE = DyeColor.PINK.getWoolData();
    protected static final Set<BaseBlock> colorBlocks = new HashSet<>();

    static {
        colorBlocks.add(new BaseBlock(Material.WOOL.getId(), COLOR_TO_REPLACE));
        colorBlocks.add(new BaseBlock(Material.STAINED_GLASS.getId(), COLOR_TO_REPLACE));
        colorBlocks.add(new BaseBlock(Material.CLAY.getId(), COLOR_TO_REPLACE));
        colorBlocks.add(new BaseBlock(Material.STAINED_GLASS_PANE.getId(), COLOR_TO_REPLACE));
        colorBlocks.add(new BaseBlock(Material.CARPET.getId(), COLOR_TO_REPLACE));
    }

    @Override
    public void replaceTeamColor(Clipboard clipboard, DyeColor c) throws WorldEditException {
        Vector minimum = clipboard.getRegion().getMinimumPoint();
        Map<BaseBlock, BaseBlock> replaceMap = new HashMap<>();
        colorBlocks.forEach(base -> replaceMap.put(base, new BaseBlock(base.getId(), c.getWoolData())));

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

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

    @Override
    public void pasteClipboard(Clipboard clipboard, Location position, org.bukkit.util.Vector offset, AffineTransform aT) {
        World w = new BukkitWorld(position.getWorld());
        EditSession e = WorldEdit.getInstance().getEditSessionFactory().getEditSession(w, -1);
        ClipboardHolder ch = new ClipboardHolder(clipboard, w.getWorldData());
        ch.setTransform(aT);
        Operations.completeBlindly(ch.createPaste(e, w.getWorldData()).to(new Vector(position.getX(), position.getY(), position.getZ()).add(
                aT.apply(new Vector(offset.getX(), offset.getY(), offset.getZ()).add(clipboard.getOrigin()).subtract(clipboard.getMinimumPoint()))
        ).toBlockPoint()).build());
        e.flushQueue();
    }

    @Override
    public org.bukkit.util.Vector getDimensions(Clipboard clipboard) {
        Vector dims = clipboard.getDimensions();
        return new org.bukkit.util.Vector(dims.getBlockX(), dims.getBlockY(), dims.getBlockZ());
    }

    @Override
    public Clipboard loadChar(String charName) throws IOException {
        return new SchematicReader(new NBTInputStream(new GZIPInputStream(new FileInputStream(new File(FightSystem.getPlugin().getDataFolder(), "text/" + charName + ".schematic"))))).read(new BukkitWorld(Config.world).getWorldData());
    }

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

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

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ClipboardWriter writer = ClipboardFormat.SCHEMATIC.getWriter(outputStream);
            writer.write(clipboard, w.getWorldData());
            writer.close();
        } catch (IOException e) {
            throw new SecurityException(e);
        }

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