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

import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.utils.FlatteningWrapper;
import de.steamwar.linkage.Linked;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

import java.util.HashSet;
import java.util.Set;

@Linked
public class WorldEditListener implements Listener {

    @EventHandler(priority = EventPriority.LOWEST)
    public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent e) {
        if (!isWorldEditCommand(e.getMessage().split(" ")[0])) return;

        Player p = e.getPlayer();
        if (!Permission.BUILD.hasPermission(e.getPlayer())) {
            BauSystem.MESSAGE.send("NO_PERMISSION", p);
            e.setCancelled(true);
            e.setMessage("/");
        }
    }

    public static void addOtherCommand(String s) {
        commands.add(s);
    }

    public static void addCommandExclusion(String s) {
        commandExclusions.add(s);
    }

    private static final Set<String> commands = new HashSet<>();
    private static final Set<String> commandExclusions = new HashSet<>();
    private static final String[] shortcutCommands = {"//1", "//2", "//90", "//-90", "//180", "//p", "//c", "//flopy", "//floppy", "//flopyp", "//floppyp", "//u", "//r"};

    public static boolean isWorldEditCommand(String command) {
        for (String shortcut : shortcutCommands) {
            if (command.startsWith(shortcut)) return true;
        }
        for (String s : commands) {
            if (command.startsWith(s)) return true;
        }
        for (String s : commandExclusions) {
            if (command.startsWith(s)) return false;
        }

        return FlatteningWrapper.impl.isWorldEditCommand(command);
    }
}
