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

import de.steamwar.Reflection;
import com.comphenix.tinyprotocol.TinyProtocol;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.features.techhider.TechHiderCommand;
import de.steamwar.bausystem.region.Region;
import de.steamwar.bausystem.utils.PlayerMovementWrapper;
import de.steamwar.bausystem.utils.ScoreboardElement;
import de.steamwar.command.SWCommand;
import de.steamwar.core.CraftbukkitWrapper;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.LinkedInstance;
import de.steamwar.techhider.TechHider;
import net.md_5.bungee.api.ChatMessageType;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.io.File;
import java.util.*;
import java.util.function.BiFunction;

@Linked
public class XrayCommand extends SWCommand implements Listener, ScoreboardElement {

    public XrayCommand() {
        super("xray");
    }

    private Map<Region, Optional<TechHider>> techHiders = new HashMap<>();
    private Map<Region, Set<Material>> xrayedBlocks = new HashMap<>();
    private Map<Region, Set<Player>> hidden = new HashMap<>();

    @LinkedInstance
    public TechHiderCommand techHiderCommand;

    @Register(description = "XRAY_HELP")
    public void toggleHider(@Validator Player player) {
        Region region = Region.getRegion(player.getLocation());
        if (region.isGlobal()) {
            BauSystem.MESSAGE.send("XRAY_GLOBAL", player);
            return;
        }

        Optional<TechHider> techHider = techHiders.computeIfAbsent(region, rg -> {
            File file = rg.gameModeConfig();
            if (file == null) {
                return Optional.empty();
            }

            FileConfiguration config = YamlConfiguration.loadConfiguration(file);
            if (!config.getBoolean("Techhider.Active", false)) {
                Set<Material> blocks = new HashSet<>(Arrays.asList(Material.END_STONE, Material.IRON_BLOCK));
                xrayedBlocks.put(region, blocks);
                return Optional.of(createXray(rg, blocks));
            }

            hidden.put(rg, new HashSet<>());

            String obfuscateWith = config.getString("Techhider.ObfuscateWith", "end_stone");

            Set<Material> blocks = new HashSet<>(Arrays.asList(Material.getMaterial(obfuscateWith.toUpperCase())));
            if (obfuscateWith.equals("end_stone")) blocks.add(Material.END_STONE_BRICKS);
            xrayedBlocks.put(region, blocks);
            return Optional.of(createXray(rg, blocks));
        });
        if (!techHider.isPresent()) {
            return;
        }

        techHiderCommand.disable(region, player);
        if (hidden.get(region).contains(player)) {
            hidden.get(region).remove(player);
            BauSystem.MESSAGE.sendPrefixless("XRAY_OFF", player, ChatMessageType.ACTION_BAR);
        } else {
            hidden.get(region).add(player);
            BauSystem.MESSAGE.sendPrefixless("XRAY_ON", player, ChatMessageType.ACTION_BAR);
        }
        region.forEachChunk((x, z) -> {
            CraftbukkitWrapper.impl.sendChunk(player, x, z);
        });
    }

    private static final Class<?> position = Reflection.getClass("net.minecraft.network.protocol.game.ServerboundMovePlayerPacket$Pos");
    private static final Class<?> positionLook = Reflection.getClass("net.minecraft.network.protocol.game.ServerboundMovePlayerPacket$PosRot");

    {
        BiFunction<Player, Object, Object> positionSetter = (player, o) -> {
            Region region = Region.getRegion(player.getLocation());
            if (hidden.containsKey(region) && hidden.get(region).contains(player)) {
                Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
                    PlayerMovementWrapper.impl.setPosition(player, o);
                }, 1L);
                return null;
            }
            return o;
        };

        TinyProtocol.instance.addFilter(position, positionSetter);
        TinyProtocol.instance.addFilter(positionLook, positionSetter);
    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
        if (!event.hasItem() || event.getItem().getType().isAir()) return;
        Region region = Region.getRegion(event.getPlayer().getLocation());
        if (!(hidden.containsKey(region) && hidden.get(region).contains(event.getPlayer()))) {
            return;
        }

        Set<Material> types = xrayedBlocks.getOrDefault(region, new HashSet<>());
        if (event.getItem() != null && types.contains(event.getItem().getType())) {
            return;
        }
        if (types.contains(event.getClickedBlock().getType())) {
            event.getClickedBlock().setType(Material.AIR, false);
        } else if (types.contains(event.getClickedBlock().getRelative(event.getBlockFace()).getType())) {
            event.getClickedBlock().getRelative(event.getBlockFace()).setType(Material.AIR, false);
        }
    }

    private TechHider createXray(Region rg, Set<Material> obfuscate) {
        TechHider current = new TechHider((TechHider.LocationEvaluator) (p, cX, cY) -> {
            if (rg.buildChunkOutside(cX, cY)) return true;
            return !hidden.get(rg).contains(p);
        }, Material.STRUCTURE_VOID, obfuscate, new HashSet<>());
        current.enable();
        return current;
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        hidden.values().forEach(set -> set.remove(event.getPlayer()));
    }

    public void disable(Region region, Player player) {
        hidden.computeIfPresent(region, (rg, set) -> {
            set.remove(player);
            return set;
        });
    }

    @Override
    public ScoreboardGroup getGroup() {
        return ScoreboardGroup.OTHER;
    }

    @Override
    public int order() {
        return 0;
    }

    @Override
    public String get(Region region, Player p) {
        if (!hidden.getOrDefault(region, Collections.emptySet()).contains(p)) return null;
        return "§e" + BauSystem.MESSAGE.parse("SCOREBOARD_XRAY", p);
    }
}
