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

import de.steamwar.Reflection;
import com.comphenix.tinyprotocol.TinyProtocol;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.SWUtils;
import de.steamwar.bausystem.features.simulator.data.Simulator;
import de.steamwar.bausystem.features.simulator.data.SimulatorElement;
import de.steamwar.bausystem.features.simulator.data.SimulatorGroup;
import de.steamwar.bausystem.features.simulator.data.observer.ObserverElement;
import de.steamwar.bausystem.features.simulator.data.observer.ObserverPhase;
import de.steamwar.bausystem.features.simulator.data.redstone.RedstoneElement;
import de.steamwar.bausystem.features.simulator.data.redstone.RedstonePhase;
import de.steamwar.bausystem.features.simulator.data.tnt.TNTElement;
import de.steamwar.bausystem.features.simulator.data.tnt.TNTPhase;
import de.steamwar.bausystem.features.simulator.execute.SimulatorExecutor;
import de.steamwar.bausystem.features.simulator.gui.SimulatorGroupGui;
import de.steamwar.bausystem.features.simulator.gui.SimulatorGui;
import de.steamwar.bausystem.features.simulator.gui.base.SimulatorBaseGui;
import de.steamwar.bausystem.utils.BauMemberUpdateEvent;
import de.steamwar.bausystem.utils.ItemUtils;
import de.steamwar.bausystem.utils.RayTraceUtils;
import de.steamwar.entity.REntity;
import de.steamwar.entity.REntityServer;
import de.steamwar.entity.RFallingBlockEntity;
import de.steamwar.inventory.SWAnvilInv;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.MinVersion;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;

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

@Linked
@MinVersion(19)
public class SimulatorCursor implements Listener {

    private final World WORLD = Bukkit.getWorlds().get(0);
    private Class<?> position = Reflection.getClass("net.minecraft.network.protocol.game.ServerboundMovePlayerPacket$Pos");
    private Class<?> look = Reflection.getClass("net.minecraft.network.protocol.game.ServerboundMovePlayerPacket$Rot");
    private Class<?> positionLook = Reflection.getClass("net.minecraft.network.protocol.game.ServerboundMovePlayerPacket$PosRot");

    private Map<Player, CursorType> cursorType = Collections.synchronizedMap(new HashMap<>());
    private Map<Player, REntityServer> cursors = Collections.synchronizedMap(new HashMap<>());
    private final Set<Player> calculating = new HashSet<>();

    public static boolean isSimulatorItem(ItemStack itemStack) {
        return ItemUtils.isItem(itemStack, "simulator");
    }

    public SimulatorCursor() {
        BiFunction<Player, Object, Object> function = (player, object) -> {
            calcCursor(player);
            return object;
        };
        TinyProtocol.instance.addFilter(position, function);
        TinyProtocol.instance.addFilter(look, function);
        TinyProtocol.instance.addFilter(positionLook, function);
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        if (!Permission.BUILD.hasPermission(event.getPlayer())) return;
        Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
            calcCursor(event.getPlayer());
        }, 0);
    }

    @EventHandler
    public void onPlayerDropItem(PlayerDropItemEvent event) {
        if (!Permission.BUILD.hasPermission(event.getPlayer())) return;
        calcCursor(event.getPlayer());
    }

    @EventHandler
    public void onPlayerItemHeld(PlayerItemHeldEvent event) {
        if (!Permission.BUILD.hasPermission(event.getPlayer())) return;
        Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
            calcCursor(event.getPlayer());
        }, 1);
    }

    @EventHandler
    public void onBauMemberUpdate(BauMemberUpdateEvent event) {
        event.getChanged().forEach(this::calcCursor);
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        cursorType.remove(event.getPlayer());
        cursors.remove(event.getPlayer());
        synchronized (calculating) {
            calculating.remove(event.getPlayer());
        }
    }

    private static final Map<Player, Long> LAST_SNEAKS = new HashMap<>();

    static {
        Bukkit.getScheduler().runTaskTimer(BauSystem.getInstance(), () -> {
            long millis = System.currentTimeMillis();
            LAST_SNEAKS.entrySet().removeIf(entry -> millis - entry.getValue() > 200);
        }, 1, 1);
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerToggleSneak(PlayerToggleSneakEvent event) {
        if (!event.isSneaking()) return;
        Player player = event.getPlayer();
        if (!isSimulatorItem(player.getInventory().getItemInMainHand()) && !isSimulatorItem(player.getInventory().getItemInOffHand())) {
            return;
        }
        if (LAST_SNEAKS.containsKey(player)) {
            cursorType.put(player, cursorType.getOrDefault(player, CursorType.TNT).switchType());
            calcCursor(player);
        } else {
            LAST_SNEAKS.put(player, System.currentTimeMillis());
        }
    }

    public void calcCursor(Player player) {
        synchronized (calculating) {
            if (calculating.contains(player)) return;
            calculating.add(player);
        }
        if (!Permission.BUILD.hasPermission(player) || (!isSimulatorItem(player.getInventory().getItemInMainHand()) && !isSimulatorItem(player.getInventory().getItemInOffHand()))) {
            if (removeCursor(player) || SimulatorWatcher.show(null, player)) {
                SWUtils.sendToActionbar(player, "");
            }
            synchronized (calculating) {
                calculating.remove(player);
            }
            return;
        }
        Simulator simulator = SimulatorStorage.getSimulator(player);
        SimulatorWatcher.show(simulator, player);

        List<REntity> entities = SimulatorWatcher.getEntitiesOfSimulator(simulator);
        RayTraceUtils.RRayTraceResult rayTraceResult = RayTraceUtils.traceREntity(player, player.getLocation(), entities);
        if (rayTraceResult == null) {
            removeCursor(player);
            if (simulator == null) {
                SWUtils.sendToActionbar(player, "§eSelect Simulator");
            } else {
                SWUtils.sendToActionbar(player, "§eOpen Simulator");
            }
            synchronized (calculating) {
                calculating.remove(player);
            }
            return;
        }

        showCursor(player, rayTraceResult, simulator != null);
        synchronized (calculating) {
            calculating.remove(player);
        }
    }

    private synchronized boolean removeCursor(Player player) {
        REntityServer entityServer = cursors.get(player);
        boolean hadCursor = entityServer != null && !entityServer.getEntities().isEmpty();
        if (entityServer != null) {
            entityServer.getEntities().forEach(REntity::die);
        }
        return hadCursor;
    }

    private synchronized void showCursor(Player player, RayTraceUtils.RRayTraceResult rayTraceResult, boolean hasSimulatorSelected) {
        REntityServer entityServer = cursors.computeIfAbsent(player, __ -> {
            REntityServer rEntityServer = new REntityServer();
            rEntityServer.addPlayer(player);
            return rEntityServer;
        });

        CursorType type = cursorType.getOrDefault(player, CursorType.TNT);
        REntity hitEntity = rayTraceResult.getHitEntity();
        Location location = hitEntity != null ? new Vector(hitEntity.getX(), hitEntity.getY(), hitEntity.getZ()).toLocation(WORLD) :
                type.position.apply(player, rayTraceResult).toLocation(WORLD);

        Material material = hitEntity != null ? Material.GLASS : type.getMaterial();
        List<RFallingBlockEntity> entities = entityServer.getEntitiesByType(RFallingBlockEntity.class);
        entities.removeIf(rFallingBlockEntity -> {
            if (rFallingBlockEntity.getMaterial() != material) {
                rFallingBlockEntity.die();
                return true;
            }
            rFallingBlockEntity.move(location);
            return false;
        });
        if (entities.isEmpty()) {
            RFallingBlockEntity rFallingBlockEntity = new RFallingBlockEntity(entityServer, location, material);
            rFallingBlockEntity.setNoGravity(true);
            if (material == Material.GLASS) {
                rFallingBlockEntity.setGlowing(true);
            }
        }

        if (hasSimulatorSelected) {
            if (hitEntity != null) {
                SWUtils.sendToActionbar(player, "§eEdit Position");
            } else {
                SWUtils.sendToActionbar(player, "§eAdd new " + type.name);
            }
        } else {
            SWUtils.sendToActionbar(player, "§eCreate new Simulator");
        }
    }

    public static Vector getPosFree(Player player, RayTraceUtils.RRayTraceResult result) {
        Vector pos = result.getHitPosition();

        BlockFace face = result.getHitBlockFace();
        if (face != null) {
            switch (face) {
                case DOWN:
                    pos.setY(pos.getY() - 0.98);
                    break;
                case EAST:
                    pos.setX(pos.getX() + 0.49);
                    break;
                case WEST:
                    pos.setX(pos.getX() - 0.49);
                    break;
                case NORTH:
                    pos.setZ(pos.getZ() - 0.49);
                    break;
                case SOUTH:
                    pos.setZ(pos.getZ() + 0.49);
                    break;
                default:
                    break;
            }

            if (face.getModY() == 0 && player.isSneaking()) {
                pos.setY(pos.getY() - 0.49);
            }
        }

        if (!player.isSneaking()) {
            pos.setX(pos.getBlockX() + 0.5);
            if (face == null || face.getModY() == 0)
                pos.setY(pos.getBlockY() + 0.0);
            pos.setZ(pos.getBlockZ() + 0.5);
        }

        return pos;
    }

    private static Vector getPosBlockAligned(Player player, RayTraceUtils.RRayTraceResult result) {
        Vector pos = result.getHitPosition();

        BlockFace face = result.getHitBlockFace();
        if (face != null) {
            switch (face) {
                case DOWN:
                    pos.setY(pos.getY() - 0.98);
                    break;
                case EAST:
                    pos.setX(pos.getX() + 0.49);
                    break;
                case WEST:
                    pos.setX(pos.getX() - 0.49);
                    break;
                case NORTH:
                    pos.setZ(pos.getZ() - 0.49);
                    break;
                case SOUTH:
                    pos.setZ(pos.getZ() + 0.49);
                    break;
                default:
                    break;
            }
        }

        pos.setX(pos.getBlockX() + 0.5);
        if (pos.getY() - pos.getBlockY() != 0 && face == BlockFace.UP) {
            pos.setY(pos.getBlockY() + 1.0);
        } else {
            pos.setY(pos.getBlockY());
        }
        pos.setZ(pos.getBlockZ() + 0.5);
        return pos;
    }

    @Getter
    @AllArgsConstructor
    public enum CursorType {
        TNT(Material.TNT, SimulatorCursor::getPosFree, "TNT", vector -> new TNTElement(vector).add(new TNTPhase())),
        REDSTONE_BLOCK(Material.REDSTONE_BLOCK, SimulatorCursor::getPosBlockAligned, "Redstone Block", vector -> new RedstoneElement(vector).add(new RedstonePhase())),
        OBSERVER(Material.OBSERVER, SimulatorCursor::getPosBlockAligned, "Observer", vector -> new ObserverElement(vector).add(new ObserverPhase())),
        ;

        private Material material;
        private BiFunction<Player, RayTraceUtils.RRayTraceResult, Vector> position;
        private String name;
        private Function<Vector, SimulatorElement<?>> elementFunction;

        public CursorType switchType() {
            if (this == TNT) {
                return REDSTONE_BLOCK;
            }
            if (this == REDSTONE_BLOCK) {
                return OBSERVER;
            }
            return TNT;
        }
    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        if (!Permission.BUILD.hasPermission(event.getPlayer())) return;
        if (!ItemUtils.isItem(event.getItem(), "simulator")) {
            return;
        }

        event.setCancelled(true);
        Player player = event.getPlayer();
        Simulator simulator = SimulatorStorage.getSimulator(player);

        if (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_AIR) {
            if (simulator == null) {
                return;
            }
            SimulatorExecutor.run(simulator);
            return;
        }

        if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_AIR) {
            return;
        }


        RayTraceUtils.RRayTraceResult rayTraceResult = RayTraceUtils.traceREntity(player, player.getLocation(), SimulatorWatcher.getEntitiesOfSimulator(simulator));
        if (simulator == null) {
            if (rayTraceResult == null) {
                SimulatorStorage.openSimulatorSelector(player);
            } else {
                SWAnvilInv anvilInv = new SWAnvilInv(player, "Name");
                anvilInv.setCallback(s -> {
                    Simulator sim = SimulatorStorage.getSimulator(s);
                    if (sim != null) {
                        BauSystem.MESSAGE.send("SIMULATOR_NAME_ALREADY_EXISTS", player);
                        return;
                    }
                    if (!s.matches("[a-zA-Z_0-9-]+")) {
                        BauSystem.MESSAGE.send("SIMULATOR_NAME_INVALID", player);
                        return;
                    }
                    sim = new Simulator(s);
                    SimulatorStorage.addSimulator(s, sim);
                    createElement(player, rayTraceResult, sim);
                    SimulatorStorage.setSimulator(player, sim);
                });
                anvilInv.open();
            }
            return;
        }

        if (rayTraceResult == null) {
            new SimulatorGui(player, simulator).open();
            return;
        }

        if (rayTraceResult.getHitEntity() != null) {
            REntity hitEntity = rayTraceResult.getHitEntity();
            Vector vector = new Vector(hitEntity.getX(), hitEntity.getY(), hitEntity.getZ());
            List<SimulatorElement<?>> elements = simulator.getGroups().stream().map(SimulatorGroup::getElements).flatMap(List::stream).filter(element -> {
                return element.getWorldPos().distanceSquared(vector) < (1 / 16.0) * (1 / 16.0);
            }).collect(Collectors.toList());

            switch (elements.size()) {
                case 0:
                    return;
                case 1:
                    // Open single element present in Simulator
                    SimulatorElement<?> element = elements.get(0);
                    SimulatorGroup group1 = element.getGroup(simulator);
                    SimulatorBaseGui back = new SimulatorGui(player, simulator);
                    if (group1.getElements().size() > 1) {
                        back = new SimulatorGroupGui(player, simulator, group1, back);
                    }
                    element.open(player, simulator, group1, back);
                    break;
                default:
                    List<SimulatorGroup> parents = elements.stream().map(e -> e.getGroup(simulator)).distinct().collect(Collectors.toList());
                    if (parents.size() == 1) {
                        // Open multi element present in Simulator in existing group
                        SimulatorGui simulatorGui = new SimulatorGui(player, simulator);
                        new SimulatorGroupGui(player, simulator, parents.get(0), simulatorGui).open();
                    } else {
                        // Open multi element present in Simulator in implicit group
                        SimulatorGroup group2 = new SimulatorGroup();
                        group2.setMaterial(null);
                        group2.getElements().addAll(elements);
                        SimulatorGui simulatorGui = new SimulatorGui(player, simulator);
                        new SimulatorGroupGui(player, simulator, group2, simulatorGui).open();
                    }
                    break;
            }
            return;
        }

        // Add new Element to current simulator
        createElement(player, rayTraceResult, simulator);
    }

    private void createElement(Player player, RayTraceUtils.RRayTraceResult rayTraceResult, Simulator simulator) {
        CursorType type = cursorType.getOrDefault(player, CursorType.TNT);
        Vector vector = type.position.apply(player, rayTraceResult);
        if (type == CursorType.REDSTONE_BLOCK) {
            vector.subtract(new Vector(0.5, 0, 0.5));
        }
        SimulatorElement<?> element = type.elementFunction.apply(vector);
        SimulatorGroup group = new SimulatorGroup().add(element);
        simulator.getGroups().add(group);
        SimulatorGui simulatorGui = new SimulatorGui(player, simulator);
        element.open(player, simulator, group, simulatorGui);
        SimulatorWatcher.update(simulator);
        calcCursor(player);
    }
}
