/*
 *   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.schematicsystem.commands.schematiccommand;

import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.CompoundTagBuilder;
import com.sk89q.jnbt.ListTag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.function.operation.ForwardExtentCopy;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import de.steamwar.command.AbstractSWCommand;
import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper;
import de.steamwar.command.TypeValidator;
import de.steamwar.linkage.Linked;
import de.steamwar.schematicsystem.SchematicSystem;
import de.steamwar.schematicsystem.autocheck.AutoCheckerResult;
import de.steamwar.schematicsystem.autocheck.BlockPos;
import de.steamwar.sql.*;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;

import static de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommandHelp.*;
import static de.steamwar.schematicsystem.commands.schematiccommand.SchematicCommandUtils.togglePublic;

@SuppressWarnings("unused")
@Linked
public class SchematicCommand extends SWCommand {

    public SchematicCommand() {
        super("schematic", new String[]{"schem", "/schem", "/schematic"});
    }

    @Register("help")
    public void pagedHelp(Player player, HelpPage page) {
        printHelpPage(player, page);
    }

    @Register
    public void genericHelp(Player player, String... args) {
        printHelpMainPage(player);
    }

    @Register(value = "togglepublic", noTabComplete = true)
    public void togglePublicMode(Player player) {
        SteamwarUser user = SteamwarUser.get(player.getUniqueId());
        if (!user.hasPerm(UserPerm.MODERATION)) {
            genericHelp(player);
            return;
        }

        if (togglePublic(player)) {
            SchematicSystem.MESSAGE.send("COMMAND_PUBLIC_ON", player);
        } else {
            SchematicSystem.MESSAGE.send("COMMAND_PUBLIC_OFF", player);
        }
    }

    @Mapper("publicMapper")
    public TypeMapper<SchematicNode> publicNodeTypeMapper() {
        return SchematicMapper.publicNodeTypeMapper();
    }

    @Mapper("memberMapper")
    public static TypeMapper<NodeMember> nodeMemberTypeMapper() {
        return SchematicMapper.nodeMemberTypeMapper();
    }

    @Mapper("dirMapper")
    public static TypeMapper<SchematicNode> dirNodeTypeMapper() {
        return SchematicMapper.dirNodeTypeMapper();
    }

    @Mapper("publicDirMapper")
    public static TypeMapper<SchematicNode> publicDirNodeTypeMapper() {
        return SchematicMapper.publicDirNodeTypeMapper();
    }

    @Mapper("dirStringMapper")
    public static TypeMapper<String> stringTabMapper() {
        return SchematicMapper.stringTabMapper();
    }

    @Mapper("stringMapper")
    public static TypeMapper<String> stringMapper() {
        return SchematicMapper.stringMapper();
    }

    @ClassMapper(SchematicType.class)
    public static TypeMapper<SchematicType> typeTypeMapper() {
        return SchematicMapper.typeTypeMapper();
    }

    @AbstractSWCommand.ClassMapper(value = SchematicNode.class, local = true)
    public static TypeMapper<SchematicNode> nodeTypeMapper() {
        return SchematicMapper.nodeTypeMapper();
    }

    @ClassMapper(value = GameModeConfig.class, local = true)
    public static TypeMapper<GameModeConfig<Material, String>> gameModeConfigTypeMapper() {
        return SchematicMapper.gameModeConfigTypeMapper();
    }

    @Override
    protected void sendMessage(CommandSender sender, String message, Object[] args) {
        SchematicSystem.MESSAGE.send(message, sender, args);
    }

    @Validator(value = "isSchemValidator", local = true)
    public static TypeValidator<SchematicNode> isSchemValidator() {
        return SchematicValidator.isSchemValidator();
    }

    @Validator(value = "isDirValidator", local = true)
    public static TypeValidator<SchematicNode> isDirValidator() {
        return SchematicValidator.isDirValidator();
    }

    @Validator(value = "isOwnerValidator", local = true)
    public static TypeValidator<SchematicNode> isOwnerValidator() {
        return SchematicValidator.isOwnerValidator();
    }

    @Validator(value = "isOwnerSchematicValidator", local = true)
    public static TypeValidator<SchematicNode> isOwnerSchematicValidator() {
        return SchematicValidator.isOwnerSchematicValidator();
    }

    public enum Extend {
        AUSFAHREN,
        NORMAL
    }

    private static final Function<CompoundTag, Integer> getCount = item -> item.getInt("count");
    private static final BiFunction<CompoundTag, Integer, CompoundTag> setCount = (item, count) -> item.createBuilder().putInt("count", count).build();

    public static Clipboard fixClipboard(Clipboard clipboard, AutoCheckerResult result, GameModeConfig<Material, String> type) throws Exception {
        for (BlockPos blockPos : result.getBlockScanResult().getRecords()) {
            BlockVector3 vector = BlockVector3.at(blockPos.getX(), blockPos.getY(), blockPos.getZ());
            clipboard.setBlock(vector, clipboard.getFullBlock(vector).toBaseBlock(new CompoundTag(Collections.emptyMap())));
        }

        Map<BlockPos, Set<Material>> toBeCheckedInvs = new HashMap<>();

        toBeCheckedInvs.putAll(result.getBlockScanResult().getForbiddenItems());
        toBeCheckedInvs.putAll(result.getBlockScanResult().getForbiddenNbt());

        for (Map.Entry<BlockPos, Set<Material>> entry : toBeCheckedInvs.entrySet()) {
            BlockPos pos = entry.getKey();
            Set<Material> materials = entry.getValue();
            BlockVector3 vector = BlockVector3.at(pos.getX(), pos.getY(), pos.getZ());
            BaseBlock block = clipboard.getFullBlock(vector);
            CompoundTag tag = block.getNbtData();
            CompoundTagBuilder builder = CompoundTagBuilder.create();
            List<CompoundTag> list = new ArrayList<>();
            for (CompoundTag items : tag.getList("Items", CompoundTag.class)) {
                if (materials.contains(Material.matchMaterial(items.getString("id")))) {
                    continue;
                }

                if (items.containsKey("tag")) {
                    continue;
                }

                list.add(items);
            }
            builder.put("Items", new ListTag(CompoundTag.class, list));
            clipboard.setBlock(vector, block.toBaseBlock(builder.build()));
        }

        for (Map.Entry<BlockPos, Map<Material, Integer>> posEntry : result.getBlockScanResult().getInventoryItemCounts().entrySet()) {
            BlockPos pos = posEntry.getKey();
            Material inventory = result.getBlockScanResult().getInventoryBlockType().get(pos);

            for (Map.Entry<Material, Integer> itemEntry : posEntry.getValue().entrySet()) {
                Material itemType = itemEntry.getKey();
                Integer cap = type.Schematic.getItemAmount(inventory, itemType);
                if (itemEntry.getValue() <= cap) {
                    continue;
                }

                BlockVector3 vector = BlockVector3.at(pos.getX(), pos.getY(), pos.getZ());
                BaseBlock block = clipboard.getFullBlock(vector);
                CompoundTag tag = block.getNbtData();
                CompoundTagBuilder builder = tag.createBuilder();
                List<CompoundTag> items = new ArrayList<>(tag.getList("Items", CompoundTag.class));
                Collections.reverse(items); // To let the first item be in the inventory
                List<CompoundTag> list = new ArrayList<>();
                int diff = itemEntry.getValue() - cap;
                for (CompoundTag item : items) {
                    if (item == null) {
                        continue;
                    }

                    if (diff == 0 || Material.matchMaterial(item.getString("id")) != itemType) {
                        list.add(item);
                        continue;
                    }

                    if (diff > getCount.apply(item)) {
                        diff -= getCount.apply(item);
                        continue;
                    }

                    item = setCount.apply(item, getCount.apply(item) - diff);
                    diff = 0;
                    list.add(item);
                }

                builder.put("Items", new ListTag(CompoundTag.class, list));
                clipboard.setBlock(vector, block.toBaseBlock(builder.build()));
            }
        }

        if (!result.isLimitedBlocksOK()) {
            Set<Material> toReplace = type.Schematic.Limited.stream()
                    .filter(rule -> rule.Amount == 0)
                    .flatMap(rule -> rule.Materials.stream())
                    .collect(Collectors.toSet());
            BlockState replaceType = Objects.requireNonNull(toReplace.contains(Material.END_STONE) ? BlockTypes.IRON_BLOCK : BlockTypes.END_STONE).getDefaultState();
            BlockVector3 min = clipboard.getMinimumPoint();
            BlockVector3 max = clipboard.getMaximumPoint();
            for (int i = min.x(); i <= max.x(); i++) {
                for (int j = min.y(); j <= max.y(); j++) {
                    for (int k = min.z(); k <= max.z(); k++) {
                        BlockVector3 vector = BlockVector3.at(i, j, k);
                        BaseBlock block = clipboard.getFullBlock(vector);
                        if (toReplace.contains(Material.matchMaterial(block.getBlockType().id()))) {
                            clipboard.setBlock(vector, replaceType.toBaseBlock());
                        }
                    }
                }
            }
        }

        return clipboard;
    }

    public static void createCopy(EditSession editSession, Clipboard clipboard) throws WorldEditException {
        Operations.complete(new ForwardExtentCopy(editSession, clipboard.getRegion(), clipboard, clipboard.getMinimumPoint()));
    }
}
