/*
 *   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.features.script.lua.libs;

import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.BukkitPlayer;
import com.sk89q.worldedit.math.BlockVector3;
import de.steamwar.bausystem.region.Point;
import de.steamwar.bausystem.utils.FlatteningWrapper;
import de.steamwar.linkage.Linked;
import org.bukkit.entity.Player;
import org.luaj.vm2.LuaTable;

@Linked
public class WorldEditLib implements LuaLib {
    @Override
    public String name() {
        return "_worldedit";
    }

    @Override
    public LuaTable get(Player player) {
        LuaTable table = new LuaTable();
        table.set("selection", getterAndSetter("selection", () -> {
            LuaTable selection = new LuaTable();
            selection.set("min", posFromVec(WorldEdit.getInstance().getSessionManager().get(new BukkitPlayer(player)).getSelectionWorld().getMinimumPoint()));
            selection.set("max", posFromVec(WorldEdit.getInstance().getSessionManager().get(new BukkitPlayer(player)).getSelectionWorld().getMaximumPoint()));
            return selection;
        }, o -> {
            LuaTable selection = o.checktable();
            if (selection.length() != 2) {
                throw new IllegalArgumentException("selection must have exactly 2 elements");
            }

            Point one = vecFromPos(selection.get(1).checktable());
            Point two = vecFromPos(selection.get(2).checktable());

            FlatteningWrapper.impl.setSelection(player, one, two);
        }));
        return table;
    }

    public static LuaTable posFromVec(BlockVector3 vec) {
        LuaTable table = new LuaTable();
        table.set("x", vec.getBlockX());
        table.set("y", vec.getBlockY());
        table.set("z", vec.getBlockZ());
        return table;
    }

    public static Point vecFromPos(LuaTable table) {
        return new Point(table.get("x").checkint(), table.get("y").checkint(), table.get("z").checkint());
    }
}
