/*
 *   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.bausystem.features.worldedit;

import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import de.steamwar.bausystem.features.world.WorldEditListener;
import de.steamwar.bausystem.features.worldedit.utils.SpecialReplace;
import de.steamwar.bausystem.shared.Pair;
import de.steamwar.bausystem.utils.WorldEditUtils;
import de.steamwar.command.PreviousArguments;
import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.MinVersion;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.type.Fence;
import org.bukkit.block.data.type.Wall;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import static org.bukkit.Material.*;

@Linked
@MinVersion(18)
public class TypeReplaceCommand extends SWCommand {

    public TypeReplaceCommand() {
        super("/typereplace", "/tr");
    }

    {
        WorldEditListener.addOtherCommand("//typereplace");
        WorldEditListener.addOtherCommand("//tr");
    }

    @Register(description = "TYPEREPLACE_HELP")
    @SneakyThrows
    public void genericCommand(@Validator Player player, Pair<Integer, Type> from, Type to) {
        if (from.getValue() == to) {
            BukkitAdapter.adapt(player).printInfo(TranslatableComponent.of("worldedit.replace.replaced", new Component[]{TextComponent.of(0)}));
            return;
        }

        try {
            Region region = WorldEditUtils.getRegion(player);
            EditSession editSession = WorldEditUtils.getEditSession(player);

            SpecialReplace specialReplace = new SpecialReplace(editSession, to.replacements(from.getValue()), from.getKey(), (oldBlockData, newBlockData) -> {
                if (newBlockData instanceof Fence && oldBlockData instanceof Wall) {
                    Wall wall = (Wall) oldBlockData;
                    Fence fence = (Fence) newBlockData;
                    fence.setWaterlogged(wall.isWaterlogged());
                    fence.setFace(BlockFace.NORTH, wall.getHeight(BlockFace.NORTH) != Wall.Height.NONE);
                    fence.setFace(BlockFace.EAST, wall.getHeight(BlockFace.EAST) != Wall.Height.NONE);
                    fence.setFace(BlockFace.SOUTH, wall.getHeight(BlockFace.SOUTH) != Wall.Height.NONE);
                    fence.setFace(BlockFace.WEST, wall.getHeight(BlockFace.WEST) != Wall.Height.NONE);
                }
                if (newBlockData instanceof Wall && oldBlockData instanceof Fence) {
                    Wall wall = (Wall) newBlockData;
                    Fence fence = (Fence) oldBlockData;
                    wall.setWaterlogged(fence.isWaterlogged());
                    wall.setHeight(BlockFace.NORTH, fence.hasFace(BlockFace.NORTH) ? Wall.Height.LOW : Wall.Height.NONE);
                    wall.setHeight(BlockFace.EAST, fence.hasFace(BlockFace.EAST) ? Wall.Height.LOW : Wall.Height.NONE);
                    wall.setHeight(BlockFace.SOUTH, fence.hasFace(BlockFace.SOUTH) ? Wall.Height.LOW : Wall.Height.NONE);
                    wall.setHeight(BlockFace.WEST, fence.hasFace(BlockFace.WEST) ? Wall.Height.LOW : Wall.Height.NONE);
                }
            });
            int affected = editSession.replaceBlocks(region, specialReplace, specialReplace);
            editSession.flushSession();
            WorldEditUtils.addToPlayer(player, editSession);
            BukkitAdapter.adapt(player).printInfo(TranslatableComponent.of("worldedit.replace.replaced", new Component[]{TextComponent.of(affected)}));
        } catch (IncompleteRegionException e) {
            BukkitAdapter.adapt(player).printError(TranslatableComponent.of("worldedit.error.incomplete-region"));
        }
    }

    @ClassMapper(value = Pair.class, local = true)
    public TypeMapper<Pair<Integer, Type>> typeMapper() {
        return new TypeMapper<Pair<Integer, Type>>() {
            @Override
            public Pair<Integer, Type> map(CommandSender commandSender, PreviousArguments previousArguments, String s) {
                if (s.contains("%")) {
                    String[] split = s.split("%");
                    if (split.length != 2) {
                        return null;
                    }
                    Type type = Type.valueOf(split[1].toUpperCase());
                    try {
                        return new Pair<>(Integer.parseInt(split[0]), type);
                    } catch (NumberFormatException e) {
                        return null;
                    }
                }
                return new Pair<>(100, Type.valueOf(s.toUpperCase()));
            }

            @Override
            public Collection<String> tabCompletes(CommandSender commandSender, PreviousArguments previousArguments, String s) {
                if (s.matches("[0-9].*")) {
                    if (s.contains("%")) {
                        String sub = s.substring(0, s.indexOf("%") + 1);
                        return Arrays.stream(Type.values()).map(Type::name).map(t -> sub + t.toLowerCase()).collect(Collectors.toSet());
                    } else {
                        return Arrays.asList(s);
                    }
                } else {
                    return Arrays.stream(Type.values()).map(Type::name).map(String::toLowerCase).collect(Collectors.toSet());
                }
            }
        };
    }

    @AllArgsConstructor
    private enum Type {
        IRON(IRON_BLOCK, null, null, null, null, null, null, IRON_BARS, IRON_DOOR, IRON_TRAPDOOR, null, HEAVY_WEIGHTED_PRESSURE_PLATE, null, null, null, null),
        WARPED(WARPED_PLANKS, WARPED_SLAB, WARPED_STAIRS, WARPED_STEM, STRIPPED_WARPED_STEM, WARPED_HYPHAE, STRIPPED_WARPED_HYPHAE, WARPED_FENCE, WARPED_DOOR, WARPED_TRAPDOOR, WARPED_FENCE_GATE, WARPED_PRESSURE_PLATE, WARPED_BUTTON, WARPED_SIGN, WARPED_WALL_SIGN, WARPED_WART_BLOCK),
        CRIMSON(CRIMSON_PLANKS, CRIMSON_SLAB, CRIMSON_STAIRS, CRIMSON_STEM, STRIPPED_CRIMSON_STEM, CRIMSON_HYPHAE, STRIPPED_CRIMSON_HYPHAE, CRIMSON_FENCE, CRIMSON_DOOR, CRIMSON_TRAPDOOR, CRIMSON_FENCE_GATE, CRIMSON_PRESSURE_PLATE, CRIMSON_BUTTON, CRIMSON_SIGN, CRIMSON_WALL_SIGN, NETHER_WART_BLOCK),
        MANGROVE(MANGROVE_PLANKS, MANGROVE_SLAB, MANGROVE_STAIRS, MANGROVE_LOG, STRIPPED_MANGROVE_LOG, MANGROVE_WOOD, STRIPPED_MANGROVE_WOOD, MANGROVE_FENCE, MANGROVE_DOOR, MANGROVE_TRAPDOOR, MANGROVE_FENCE_GATE, MANGROVE_PRESSURE_PLATE, MANGROVE_BUTTON, MANGROVE_SIGN, MANGROVE_WALL_SIGN, MANGROVE_LEAVES),
        DARK_OAK(DARK_OAK_PLANKS, DARK_OAK_SLAB, DARK_OAK_STAIRS, DARK_OAK_LOG, STRIPPED_DARK_OAK_LOG, DARK_OAK_WOOD, STRIPPED_DARK_OAK_WOOD, DARK_OAK_FENCE, DARK_OAK_DOOR, DARK_OAK_TRAPDOOR, DARK_OAK_FENCE_GATE, DARK_OAK_PRESSURE_PLATE, DARK_OAK_BUTTON, DARK_OAK_SIGN, DARK_OAK_WALL_SIGN, DARK_OAK_LEAVES),
        ACACIA(ACACIA_PLANKS, ACACIA_SLAB, ACACIA_STAIRS, ACACIA_LOG, STRIPPED_ACACIA_LOG, ACACIA_WOOD, STRIPPED_ACACIA_WOOD, ACACIA_FENCE, ACACIA_DOOR, ACACIA_TRAPDOOR, ACACIA_FENCE_GATE, ACACIA_PRESSURE_PLATE, ACACIA_BUTTON, ACACIA_SIGN, ACACIA_WALL_SIGN, ACACIA_LEAVES),
        JUNGLE(JUNGLE_PLANKS, JUNGLE_SLAB, JUNGLE_STAIRS, JUNGLE_LOG, STRIPPED_JUNGLE_LOG, JUNGLE_WOOD, STRIPPED_JUNGLE_WOOD, JUNGLE_FENCE, JUNGLE_DOOR, JUNGLE_TRAPDOOR, JUNGLE_FENCE_GATE, JUNGLE_PRESSURE_PLATE, JUNGLE_BUTTON, JUNGLE_SIGN, JUNGLE_WALL_SIGN, JUNGLE_LEAVES),
        BIRCH(BIRCH_PLANKS, BIRCH_SLAB, BIRCH_STAIRS, BIRCH_LOG, STRIPPED_BIRCH_LOG, BIRCH_WOOD, STRIPPED_BIRCH_WOOD, BIRCH_FENCE, BIRCH_DOOR, BIRCH_TRAPDOOR, BIRCH_FENCE_GATE, BIRCH_PRESSURE_PLATE, BIRCH_BUTTON, BIRCH_SIGN, BIRCH_WALL_SIGN, BIRCH_LEAVES),
        SPRUCE(SPRUCE_PLANKS, SPRUCE_SLAB, SPRUCE_STAIRS, SPRUCE_LOG, STRIPPED_SPRUCE_LOG, SPRUCE_WOOD, STRIPPED_SPRUCE_WOOD, SPRUCE_FENCE, SPRUCE_DOOR, SPRUCE_TRAPDOOR, SPRUCE_FENCE_GATE, SPRUCE_PRESSURE_PLATE, SPRUCE_BUTTON, SPRUCE_SIGN, SPRUCE_WALL_SIGN, SPRUCE_LEAVES),
        OAK(OAK_PLANKS, OAK_SLAB, OAK_STAIRS, OAK_LOG, STRIPPED_OAK_LOG, OAK_WOOD, STRIPPED_OAK_WOOD, OAK_FENCE, OAK_DOOR, OAK_TRAPDOOR, OAK_FENCE_GATE, OAK_PRESSURE_PLATE, OAK_BUTTON, OAK_SIGN, OAK_WALL_SIGN, OAK_LEAVES),
        STONE(Material.STONE, STONE_SLAB, STONE_STAIRS, null, null, null, null, null, null, null, null, STONE_PRESSURE_PLATE, STONE_BUTTON, null, null, null),
        COBBLE(COBBLESTONE, COBBLESTONE_SLAB, COBBLESTONE_STAIRS, COBBLESTONE_WALL),
        DEEPSLATE_COBBLE(COBBLED_DEEPSLATE, COBBLED_DEEPSLATE_SLAB, COBBLED_DEEPSLATE_STAIRS, COBBLED_DEEPSLATE_WALL),
        DEEPSLATE_POLISHED(POLISHED_DEEPSLATE, POLISHED_DEEPSLATE_SLAB, POLISHED_DEEPSLATE_STAIRS, POLISHED_DEEPSLATE_WALL),
        DEEPSLATE_BRICKS(Material.DEEPSLATE_BRICKS, DEEPSLATE_BRICK_SLAB, DEEPSLATE_BRICK_STAIRS, DEEPSLATE_BRICK_WALL),
        DEEPSLATE_TILES(Material.DEEPSLATE_TILES, DEEPSLATE_TILE_SLAB, DEEPSLATE_TILE_STAIRS, DEEPSLATE_TILE_WALL),
        BLACKSTONE(Material.BLACKSTONE, BLACKSTONE_SLAB, BLACKSTONE_STAIRS, BLACKSTONE_WALL),
        BLACKSTONE_POLISHED(POLISHED_BLACKSTONE, POLISHED_BLACKSTONE_SLAB, POLISHED_BLACKSTONE_STAIRS, CHISELED_POLISHED_BLACKSTONE, null, null, null, POLISHED_BLACKSTONE_WALL, null, null, null, POLISHED_BLACKSTONE_PRESSURE_PLATE, POLISHED_BLACKSTONE_BUTTON, null, null, null),
        BLACKSTONE_BRICKS(POLISHED_BLACKSTONE_BRICKS, POLISHED_BLACKSTONE_BRICK_SLAB, POLISHED_BLACKSTONE_BRICK_STAIRS, POLISHED_BLACKSTONE_BRICK_WALL),
        ANDESITE(Material.ANDESITE, ANDESITE_SLAB, ANDESITE_STAIRS, ANDESITE_WALL),
        ANDESITE_POLISHED(POLISHED_ANDESITE, POLISHED_ANDESITE_SLAB, POLISHED_ANDESITE_STAIRS, null),
        DIORITE(Material.DIORITE, DIORITE_SLAB, DIORITE_STAIRS, DIORITE_WALL),
        DIORITE_POLISHED(POLISHED_DIORITE, POLISHED_DIORITE_SLAB, POLISHED_DIORITE_STAIRS, null),
        GRANITE(Material.GRANITE, GRANITE_SLAB, GRANITE_STAIRS, GRANITE_WALL),
        GRANITE_POLISHED(POLISHED_GRANITE, POLISHED_GRANITE_SLAB, POLISHED_GRANITE_STAIRS, null),
        COBBLE_MOSSY(MOSSY_COBBLESTONE, MOSSY_COBBLESTONE_SLAB, MOSSY_COBBLESTONE_STAIRS, MOSSY_COBBLESTONE_WALL),
        STONE_BRICKS_MOSSY(MOSSY_STONE_BRICKS, MOSSY_STONE_BRICK_SLAB, MOSSY_STONE_BRICK_STAIRS, MOSSY_STONE_BRICK_WALL),
        MUD_BRICKS(Material.MUD_BRICKS, MUD_BRICK_SLAB, MUD_BRICK_STAIRS, MUD_BRICK_WALL),
        SANDSTONE(Material.SANDSTONE, SANDSTONE_SLAB, SANDSTONE_STAIRS, CUT_SANDSTONE, CHISELED_SANDSTONE, SAND, SANDSTONE_WALL),
        SANDSTONE_SMOOTH(SMOOTH_SANDSTONE, SMOOTH_SANDSTONE_SLAB, SMOOTH_SANDSTONE_STAIRS, CUT_SANDSTONE, CHISELED_SANDSTONE, SAND, null),
        RED_SANDSTONE(Material.RED_SANDSTONE, RED_SANDSTONE_SLAB, RED_SANDSTONE_STAIRS, CUT_RED_SANDSTONE, CHISELED_RED_SANDSTONE, RED_SAND, RED_SANDSTONE_WALL),
        RED_SANDSTONE_SMOOTH(SMOOTH_RED_SANDSTONE, SMOOTH_RED_SANDSTONE_SLAB, SMOOTH_RED_SANDSTONE_STAIRS, CUT_RED_SANDSTONE, CHISELED_RED_SANDSTONE, RED_SAND, null),
        SMOOTHSTONE(Material.SMOOTH_STONE, SMOOTH_STONE_SLAB, null, null),
        CUT_COPPER(WAXED_CUT_COPPER, WAXED_CUT_COPPER_SLAB, WAXED_CUT_COPPER_STAIRS, null),
        EXPOSED_CUT_COPPER(WAXED_EXPOSED_CUT_COPPER, WAXED_EXPOSED_CUT_COPPER_SLAB, WAXED_EXPOSED_CUT_COPPER_STAIRS, null),
        WEATHERED_CUT_COPPER(WAXED_WEATHERED_CUT_COPPER, WAXED_WEATHERED_CUT_COPPER_SLAB, WAXED_WEATHERED_CUT_COPPER_STAIRS, null),
        OXIDIZED_CUT_COPPER(WAXED_OXIDIZED_CUT_COPPER, WAXED_OXIDIZED_CUT_COPPER_SLAB, WAXED_OXIDIZED_CUT_COPPER_STAIRS, null),
        END_STONE_BRICKS(Material.END_STONE_BRICKS, END_STONE_BRICK_SLAB, END_STONE_BRICK_STAIRS, END_STONE_BRICK_WALL),
        PURPUR(PURPUR_BLOCK, PURPUR_SLAB, PURPUR_STAIRS, PURPUR_PILLAR, null, null, null),
        RED_NETHER_BRICKS(Material.RED_NETHER_BRICKS, RED_NETHER_BRICK_SLAB, RED_NETHER_BRICK_STAIRS, RED_NETHER_BRICK_WALL),
        NETHER_BRICKS_WITH_WALL(NETHER_BRICKS, NETHER_BRICK_SLAB, NETHER_BRICK_STAIRS, CHISELED_NETHER_BRICKS, null, null, NETHER_BRICK_WALL),
        NETHER_BRICKS_WITH_FENCE(NETHER_BRICKS, NETHER_BRICK_SLAB, NETHER_BRICK_STAIRS, NETHER_BRICK_FENCE),
        BASALT(Material.BASALT, null, null, POLISHED_BASALT, SMOOTH_BASALT, null, null),
        PRISMARINE_DARK(DARK_PRISMARINE, DARK_PRISMARINE_SLAB, DARK_PRISMARINE_STAIRS, null),
        PRISMARINE(Material.PRISMARINE, PRISMARINE_SLAB, PRISMARINE_STAIRS, PRISMARINE_WALL),
        PRISMARINE_BRICKS(Material.PRISMARINE_BRICKS, PRISMARINE_BRICK_SLAB, PRISMARINE_BRICK_STAIRS, null),
        QUARTZ_SMOOTH(SMOOTH_QUARTZ, SMOOTH_QUARTZ_SLAB, SMOOTH_QUARTZ_STAIRS, QUARTZ_PILLAR, QUARTZ_BRICKS, CHISELED_QUARTZ_BLOCK, null),
        QUARTZ(Material.QUARTZ_BLOCK, QUARTZ_SLAB, QUARTZ_STAIRS, QUARTZ_PILLAR, QUARTZ_BRICKS, CHISELED_QUARTZ_BLOCK, null),
        STONE_BRICKS(Material.STONE_BRICKS, STONE_BRICK_SLAB, STONE_BRICK_STAIRS, CHISELED_STONE_BRICKS, null, CRACKED_STONE_BRICKS, STONE_BRICK_WALL),
        BRICKS(Material.BRICKS, BRICK_SLAB, BRICK_STAIRS, BRICK_WALL);

        Type(Material base, Material slab, Material stairs, Material fence) {
            this.base = base;
            this.slab = slab;
            this.stairs = stairs;
            this.fence = fence;
        }

        Type(Material base, Material slab, Material stairs, Material log, Material strippedLog, Material allSided, Material fence) {
            this.base = base;
            this.slab = slab;
            this.stairs = stairs;
            this.log = log;
            this.strippedLog = strippedLog;
            this.allSided = allSided;
            this.fence = fence;
        }

        private Material base;
        private Material slab;
        private Material stairs;
        private Material log;
        private Material strippedLog;
        private Material allSided;
        private Material strippedAllSided;
        private Material fence;
        private Material doors;
        private Material trapdoors;
        private Material fenceGates;
        private Material pressurePlates;
        private Material button;
        private Material signs;
        private Material wallSigns;
        private Material leaves;

        private Map<String, String> replacements(Type from) {
            Map<String, String> replacements = new HashMap<>();
            if (base != null && from.base != null) {
                replacements.put("minecraft:" + from.base.name().toLowerCase(), "minecraft:" + base.name().toLowerCase());
            }
            if (slab != null && from.slab != null) {
                replacements.put("minecraft:" + from.slab.name().toLowerCase(), "minecraft:" + slab.name().toLowerCase());
            }
            if (stairs != null && from.stairs != null) {
                replacements.put("minecraft:" + from.stairs.name().toLowerCase(), "minecraft:" + stairs.name().toLowerCase());
            }
            if (log != null && from.log != null) {
                replacements.put("minecraft:" + from.log.name().toLowerCase(), "minecraft:" + log.name().toLowerCase());
            }
            if (strippedLog != null && from.strippedLog != null) {
                replacements.put("minecraft:" + from.strippedLog.name().toLowerCase(), "minecraft:" + strippedLog.name().toLowerCase());
            }
            if (allSided != null && from.allSided != null) {
                replacements.put("minecraft:" + from.allSided.name().toLowerCase(), "minecraft:" + allSided.name().toLowerCase());
            }
            if (strippedAllSided != null && from.strippedAllSided != null) {
                replacements.put("minecraft:" + from.strippedAllSided.name().toLowerCase(), "minecraft:" + strippedAllSided.name().toLowerCase());
            }
            if (fence != null && from.fence != null) {
                replacements.put("minecraft:" + from.fence.name().toLowerCase(), "minecraft:" + fence.name().toLowerCase());
            }
            if (doors != null && from.doors != null) {
                replacements.put("minecraft:" + from.doors.name().toLowerCase(), "minecraft:" + doors.name().toLowerCase());
            }
            if (trapdoors != null && from.trapdoors != null) {
                replacements.put("minecraft:" + from.trapdoors.name().toLowerCase(), "minecraft:" + trapdoors.name().toLowerCase());
            }
            if (fenceGates != null && from.fenceGates != null) {
                replacements.put("minecraft:" + from.fenceGates.name().toLowerCase(), "minecraft:" + fenceGates.name().toLowerCase());
            }
            if (pressurePlates != null && from.pressurePlates != null) {
                replacements.put("minecraft:" + from.pressurePlates.name().toLowerCase(), "minecraft:" + pressurePlates.name().toLowerCase());
            }
            if (button != null && from.button != null) {
                replacements.put("minecraft:" + from.button.name().toLowerCase(), "minecraft:" + button.name().toLowerCase());
            }
            if (signs != null && from.signs != null) {
                replacements.put("minecraft:" + from.signs.name().toLowerCase(), "minecraft:" + signs.name().toLowerCase());
            }
            if (wallSigns != null && from.wallSigns != null) {
                replacements.put("minecraft:" + from.wallSigns.name().toLowerCase(), "minecraft:" + wallSigns.name().toLowerCase());
            }
            if (leaves != null && from.leaves != null) {
                replacements.put("minecraft:" + from.leaves.name().toLowerCase(), "minecraft:" + leaves.name().toLowerCase());
            }
            return replacements;
        }
    }
}
