/*
 *   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.BauSystem;
import de.steamwar.bausystem.Permission;
import de.steamwar.bausystem.features.script.ScriptRunner;
import de.steamwar.linkage.Linked;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;

@Linked
public class HotkeyListener implements PluginMessageListener {

    {
        Bukkit.getServer().getMessenger().registerIncomingPluginChannel(BauSystem.getInstance(), "sw:hotkeys", this);
    }

    @Override
    public void onPluginMessageReceived(String channel, Player player, byte[] message) {
        if (!Permission.BUILD.hasPermission(player)) return;
        if (!channel.equals("sw:hotkeys")) return;
        if (message.length < 5) return;
        int action = message[4] & 0xFF;
        if (action == 2) return;
        int key = (message[0] & 0xFF) << 24 | (message[1] & 0xFF) << 16 | (message[2] & 0xFF) << 8 | (message[3] & 0xFF);
        if (!(key >= 'A' && key <= 'Z' || key >= '0' && key <= '9')) return;
        if (message.length >= 9) {
            int mods = (message[5] & 0xFF) << 24 | (message[6] & 0xFF) << 16 | (message[7] & 0xFF) << 8 | (message[8] & 0xFF);
            // player.sendMessage("Hotkey: " + (char) key + " " + action + " " + Long.toBinaryString(mods));
            ScriptRunner.callHotkey(mods, key, player, action == 1);
        } else {
            // player.sendMessage("Hotkey: " + (char) key + " " + action);
            ScriptRunner.callHotkey(0, key, player, action == 1);
        }
    }

}
