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

import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.features.script.ScriptRunner;
import de.steamwar.linkage.Linked;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Linked
public class CommandListener implements Listener {

    private Map<Player, Set<String>> calledCommands = new HashMap<>();

    @EventHandler
    public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
        if(!Permission.BUILD.hasPermission(event.getPlayer())) return;
        String[] split = event.getMessage().split(" ");
        if (calledCommands.getOrDefault(event.getPlayer(), new HashSet<>()).contains(split[0])) {
            return;
        }

        calledCommands.getOrDefault(event.getPlayer(), new HashSet<>()).add(split[0]);
        event.setCancelled(ScriptRunner.callCommand(event.getPlayer(), split[0].substring(1), split));
        calledCommands.getOrDefault(event.getPlayer(), new HashSet<>()).remove(split[0]);
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        calledCommands.put(event.getPlayer(), new HashSet<>());
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        calledCommands.remove(event.getPlayer());
    }
}
