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

import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.IncompleteRegionException;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extension.factory.PatternFactory;
import com.sk89q.worldedit.extension.platform.permission.ActorSelectorLimits;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.internal.registry.InputParser;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.regions.selector.limit.SelectorLimits;
import de.steamwar.Reflection;
import de.steamwar.bausystem.shared.Pair;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;

import java.util.List;
import java.util.stream.Collectors;

@UtilityClass
public class WorldEditUtils {

    public EditSession getEditSession(Player player) {
        return WorldEdit.getInstance().getEditSessionFactory().getEditSession(BukkitAdapter.adapt(player.getWorld()), -1, BukkitAdapter.adapt(player));
    }

    public void addToPlayer(Player player, EditSession editSession) {
        WorldEdit.getInstance().getSessionManager().get(BukkitAdapter.adapt(player)).remember(editSession);
    }

    @SneakyThrows
    public Region getRegion(Player player) {
        RegionSelector regionSelector = WorldEdit.getInstance()
                .getSessionManager()
                .get(BukkitAdapter.adapt(player))
                .getRegionSelector(BukkitAdapter.adapt(player.getWorld()));
        return regionSelector.getRegion();
    }

    @SneakyThrows
    public Mask getMask(Player player) {
        return WorldEdit.getInstance()
                .getSessionManager()
                .get(BukkitAdapter.adapt(player))
                .getMask();
    }

    public void addMaskParser(InputParser<Mask> maskInputParser) {
        WorldEdit.getInstance().getMaskFactory().register(maskInputParser);
    }

    public void addPatternParser(InputParser<Pattern> patternInputParser) {
        WorldEdit.getInstance().getPatternFactory().register(patternInputParser);
    }

    public PatternFactory getPatternFactory() {
        return WorldEdit.getInstance().getPatternFactory();
    }

    public Pair<Class<? extends RegionSelector>, List<Location>> getVertices(Player player) {
        RegionSelector regionSelector = WorldEdit.getInstance()
                .getSessionManager()
                .get(BukkitAdapter.adapt(player))
                .getRegionSelector(BukkitAdapter.adapt(player.getWorld()));
        return new Pair<>(regionSelector.getClass(), regionSelector.getVertices()
                .stream()
                .map(blockVector3 -> blockVector3 == null ? null : adapt(player.getWorld(), blockVector3))
                .collect(Collectors.toList()));
    }

    public void setVertices(Player player, Class<? extends RegionSelector> clazz, List<Location> vertices) {
        LocalSession localSession = WorldEdit.getInstance()
                .getSessionManager()
                .get(BukkitAdapter.adapt(player));

        Reflection.Constructor constructorInvoker = Reflection.getConstructor(clazz, com.sk89q.worldedit.world.World.class);
        RegionSelector regionSelector = (RegionSelector) constructorInvoker.invoke(BukkitAdapter.adapt(player.getWorld()));
        localSession.setRegionSelector(BukkitAdapter.adapt(player.getWorld()), regionSelector);

        if (vertices.isEmpty()) return;

        SelectorLimits selectorLimits = ActorSelectorLimits.forActor(BukkitAdapter.adapt(player));
        for (int i = 0; i < vertices.size(); i++) {
            Location location = vertices.get(i);
            if (location == null) continue;
            if (i == 0) {
                regionSelector.selectPrimary(BukkitAdapter.adapt(location).toBlockPoint(), selectorLimits);
            } else {
                regionSelector.selectSecondary(BukkitAdapter.adapt(location).toBlockPoint(), selectorLimits);
            }
        }
    }

    public Pair<Location, Location> getSelection(Player player) {
        RegionSelector regionSelector = WorldEdit.getInstance()
                .getSessionManager()
                .get(BukkitAdapter.adapt(player))
                .getRegionSelector(BukkitAdapter.adapt(player.getWorld()));

        try {
            BlockVector3 min = regionSelector.getRegion().getMinimumPoint();
            BlockVector3 max = regionSelector.getRegion().getMaximumPoint();
            return new Pair<>(adapt(player.getWorld(), min), adapt(player.getWorld(), max));
        } catch (IncompleteRegionException e) {
            return null;
        }
    }

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