/*
 *   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.lobby.command;

import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.RegionSelector;
import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper;
import de.steamwar.linkage.Linked;
import de.steamwar.lobby.LobbySystem;
import de.steamwar.lobby.portal.*;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm;
import lombok.Data;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;

@Linked
public class PortalCommand extends SWCommand {

    public PortalCommand() {
        super("portal");
    }

    public static boolean noPermissions(Player player) {
        SteamwarUser steamwarUser = SteamwarUser.get(player.getUniqueId());
        return !steamwarUser.hasPerm(UserPerm.ADMINISTRATION);
    }

    @Register
    public void genericHelp(Player player, String... args) {
        if (noPermissions(player)) return;
        LobbySystem.getMessage().sendPrefixless("COMMAND_HELP_HEAD", player, "portal");
        LobbySystem.getMessage().sendPrefixless("PORTAL_COMMAND_LIST_HELP", player);
        LobbySystem.getMessage().sendPrefixless("PORTAL_COMMAND_ADD_HELP", player);
        LobbySystem.getMessage().sendPrefixless("PORTAL_COMMAND_REMOVE_HELP", player);
    }

    @Register("list")
    public void portalList(Player player) {
        if (noPermissions(player)) return;
        LobbySystem.getMessage().sendPrefixless("COMMAND_HELP_HEAD", player, "portal list");
        Portal.getPortals().forEach(portal -> {
            LobbySystem.getMessage().sendPrefixless("PORTAL_COMMAND_LIST_SHORT_INFO", player, portal.type().name(), portal.getId(), portal.getPos1().toVector().toString(), portal.getPos2().toVector().toString());
        });
    }

    @Register({"create", "command"})
    public void portalAddCommand(Player player, String portalName, String... command) {
        if (noPermissions(player)) return;
        PortalLocations tuple = getSelection(player);
        if (tuple == null) return;
        new Portal(portalName, tuple.k, tuple.v, portal -> new CommandPortal(String.join(" ", command)));
    }

    @Register({"create", "fight"})
    public void portalAddFightserver(Player player, String portalName, String gamemode, int order, String target) {
        if (noPermissions(player)) return;
        PortalLocations tuple = getSelection(player);
        if (tuple == null) return;
        new Portal(portalName, tuple.k, tuple.v, portal -> new FightserverPortal(portal, gamemode.toLowerCase(), order, target, new ArrayList<>(), new ArrayList<>()));
    }

    @Register({"create", "teleport"})
    public void portalAddTeleport(Player player, String portalName, String portalDestination) {
        if (noPermissions(player)) return;
        PortalLocations tuple = getSelection(player);
        if (tuple == null) return;
        new Portal(portalName, tuple.k, tuple.v, portal -> new TeleportPortal(portal, portalDestination));
    }

    @Register({"create", "stack"})
    public void portalAddStack(Player player, String portalName, String portalDestination, String... command) {
        if (noPermissions(player)) return;
        PortalLocations tuple = getSelection(player);
        if (tuple == null) return;

        new Portal(portalName, tuple.k, tuple.v, portal -> new StackPortal(portal, portalDestination, String.join(" ", command)));
    }

    @Register({"depth"})
    public void portalDepth(Player player, Portal portal, @Max(doubleValue = 10.0d) double depth) {
        if (noPermissions(player)) return;
        portal.setDepth(depth);
    }

    @Register({"addblue"})
    public void portalAddBlue(Player player, Portal portal) {
        if (noPermissions(player)) return;
        FightserverPortal handler = (FightserverPortal) portal.getHandler();
        handler.addBlue(locationOfPlayer(player));
    }

    @Register({"addred"})
    public void portalAddRed(Player player, Portal portal) {
        if (noPermissions(player)) return;
        FightserverPortal handler = (FightserverPortal) portal.getHandler();
        handler.addRed(locationOfPlayer(player));
    }

    private Location locationOfPlayer(Player player) {
        Location l = player.getLocation();

        l.setYaw(((CraftPlayer)player).getHandle().cm());
        return l;
    }

    @Register({"removeblue"})
    public void portalRemoveBlue(Player player, Portal portal, int i) {
        if (noPermissions(player)) return;
        FightserverPortal handler = (FightserverPortal) portal.getHandler();
        handler.removeBlue(i-1);
    }

    @Register({"removered"})
    public void portalRemoveRed(Player player, Portal portal, int i) {
        if (noPermissions(player)) return;
        FightserverPortal handler = (FightserverPortal) portal.getHandler();
        handler.removeRed(i-1);
    }

    @Register("remove")
    public void portalRemove(Player player, Portal portal) {
        if (noPermissions(player)) return;
        portal.delete();
    }

    @ClassMapper(value = Portal.class, local = true)
    public TypeMapper<Portal> portalTypeMapper() {
        return new TypeMapper<Portal>() {
            @Override
            public List<String> tabCompletes(CommandSender commandSender, String[] strings, String s) {
                return new ArrayList<>(Portal.getPortalNames());
            }

            @Override
            public Portal map(CommandSender commandSender, String[] previousArguments, String s) {
                return Portal.getPortal(s);
            }
        };
    }

    @Data
    private static class PortalLocations {
        private final Location k;
        private final Location v;
    }

    private PortalLocations getSelection(Player player) {
        RegionSelector regionSelector = WorldEdit.getInstance()
                .getSessionManager()
                .get(BukkitAdapter.adapt(player))
                .getRegionSelector(BukkitAdapter.adapt(player.getWorld()));

        try {
            CuboidRegion region = (CuboidRegion)regionSelector.getRegion();
            return new PortalLocations(adapt(player.getWorld(), region.getPos1()), adapt(player.getWorld(), region.getPos2()));
        } catch (IncompleteRegionException e) {
            LobbySystem.getMessage().send("PORTAL_NO_WORLDEDIT_SELECTION", player);
            return null;
        }
    }

    private Location adapt(World world, BlockVector3 blockVector3) {
        return new Location(world, blockVector3.getBlockX() + 0.5, blockVector3.getBlockY(), blockVector3.getBlockZ() + 0.5);
    }
}
