import { world, system } from "@minecraft/server";
import PlotManager from "./PlotManager";
import FSPlayerPerms from "./fs/libs/perms/FSPlayerPerms";
import FSEntityPerms from "./fs/libs/perms/FSEntityPerms";
import { ADDON_PROTOCOL_VERSION } from "./fs/FSConstants";
import FSDynamicProperty from "./fs/libs/FSDynamicProperty";
import FSUtil from "./fs/FSUtil";
import FormManager from "./FormManager";
import PlayerHelper from "./PlayerHelper";
import SecurityDoor from "./entity/SecurityDoor";
import SecretEntrance from "./entity/SecretEntrance";
import ComputerMonitor from "./entity/ComputerMonitor";
import EntranceManager from "./EntranceManager";
import LockedBlock from "./entity/LockedBlock";
import EntityManager from "./EntityManager";
import FSLocalizedString from "./fs/FSLocalizedString";
import LaserBeam from "./entity/LaserBeam";
import CameraManager from "./CameraManager";
export default class ScriptEventManager {
    constructor() {
    }
    static sharedInstance() {
        if (!ScriptEventManager.instance) {
            ScriptEventManager.instance = new ScriptEventManager();
        }
        return ScriptEventManager.instance;
    }
    init() {
        system.afterEvents.scriptEventReceive.subscribe(this.handleScriptEventReceive.bind(this));
    }
    handleScriptEventReceive(eventData) {
        if (eventData.id === "57d_sbunk:poppable__did_damage") {
            const data = JSON.parse(eventData.message);
            const state = data.state;
            const identifier = data.identifier;
            const sourceEntity = eventData.sourceEntity;
            const tag = `57d_sbunk:player_did_poppable_damage__${identifier}_callback`;
            const eqo = {
                tags: [tag],
                closest: 1,
                location: sourceEntity.location,
                maxDistance: 10
            };
            const players = sourceEntity.dimension.getPlayers(eqo);
            if (players.length > 0) {
                const player = players[0];
                const meter = state === 0 ? "§c█░░" : state === 1 ? "§e██░" : "§a███";
                const message = {
                    rawtext: [
                        { text: "§a[!] §r" },
                        {
                            translate: state >= 2 ? FSLocalizedString.localize("entity.destroyed", "Destroyed! ", "Feedback to the player popping the entity.") : FSLocalizedString.localize("entity.popping", "Destroying: ", "Feedback to the player popping the entity.")
                        },
                        {
                            text: meter
                        }
                    ]
                };
                player.onScreenDisplay.setActionBar(message);
                player.removeTag(tag);
            }
            const wso = {
                pitch: 0.7 + state * 0.1,
                volume: 1.0
            };
            world.playSound("random.pop", sourceEntity.location, wso);
            if (state === 2) {
                sourceEntity.remove();
            }
        }
        if (eventData.id === "57d_sbunk:player_did_interact") {
            this.handlePlayerInteract(eventData);
        }
        if (eventData.id === "57d_sbunk:event") {
            if (eventData.message === "plots") {
                PlotManager.ProcessPlots();
            }
        }
        if (eventData.id === "57d_sbunk:test_ui") {
            world.getPlayers().forEach(player => {
                FSPlayerPerms.sharedInstance().showProfilesPicker(player);
            });
        }
        if (eventData.id === "57d_sbunk:test_unrootme") {
            world.getPlayers().forEach(player => {
                FSPlayerPerms.sharedInstance().unrootPlayer(player);
            });
        }
        if (eventData.id === "57d_sbunk:test_toggle_admin") {
            world.getPlayers().forEach(player => {
                FSPlayerPerms.sharedInstance().toggleAdmin(player);
            });
        }
        if (eventData.id === "fs:sbunk.test_entitypermsmenuui") {
            var entity = null;
            world
                .getDimension("overworld")
                .getEntities()
                .forEach(e => {
                if (e.typeId === "minecraft:armor_stand") {
                    entity = e;
                }
            });
            if (!entity) {
                world.getPlayers().forEach(player => {
                    player.sendMessage("§cNo armor stand found to run test.");
                });
                return;
            }
            else {
                world.getPlayers().forEach(player => {
                    FSEntityPerms.showEntityPermissionMenu(player, entity);
                });
            }
        }
        if (eventData.id === "57d_sbunk:reset") {
            world.getPlayers().forEach(player => {
                FSPlayerPerms.sharedInstance().reset();
                FSDynamicProperty.setBoolean(player, "hasReceivedBonusChips", false);
            });
            FSDynamicProperty.setBoolean(world, FSUtil.namespacedString("hasBuiltBunker"), false); 
            FSDynamicProperty.setBoolean(world, FSUtil.namespacedString("shouldSuppressNewCameraNotifications"), false);
            FSDynamicProperty.setBoolean(world, "hasBuiltBunker", false);
            FSDynamicProperty.clear(world, "free_chips_timestamp");
            world.sendMessage("§a[!] Security++ reset complete.");
        }
        if (eventData.id === "57d_sbunk:bring_forward_free_chip_timeout") {
            const now = new Date();
            now.setHours(now.getHours() - 3);
            const timestamp = now.getTime();
            FSDynamicProperty.setString(world, "free_chips_timestamp", timestamp.toString());
            world.sendMessage("OK");
        }
        const handshakeEvent = "57d_sbunk:handshake";
        if (eventData.id === handshakeEvent) {
            try {
                const args = JSON.parse(eventData.message);
                const callback = args.callback || "";
                if (callback.length >= 1) {
                    if (callback === handshakeEvent) {
                        console.error("Handshake protocol requires a different callback name! Aborting.");
                        return;
                    }
                    try {
                        const addonVersion = ADDON_PROTOCOL_VERSION || 0;
                        world.getDimension("overworld").runCommand(`/scriptevent ${callback} {"installed_addon":"fs_sbunk","protocol":${addonVersion}}`);
                    }
                    catch (ex) {
                    }
                }
            }
            catch (ex) {
            }
        }
        if (eventData.id === "fs_sbunk:admin_me") {
            var player = eventData.sourceEntity;
            FSPlayerPerms.sharedInstance().enableAdmin(player);
        }
        if (eventData.id === "57d_sbunk:clear_last_version") {
            FSDynamicProperty.clear(world, FSUtil.namespacedString("lastVersion"));
        }
        if (eventData.id === "57d_sbunk:dev_reset_versioning") {
            FSDynamicProperty.setNumber(world, FSUtil.namespacedString("lastVersion"), 2);
            FSDynamicProperty.setBoolean(world, FSUtil.namespacedString("hasUsedInitialRelease"), true); 
            FSDynamicProperty.setBoolean(world, FSUtil.namespacedString("shouldShowMigrationMessage"), true); 
            FSDynamicProperty.setBoolean(world, FSUtil.namespacedString("shouldShowMigrationTabletMessage"), true); 
        }
        if (eventData.id === "57d_sbunk:test_rating") {
            var date = new Date();
            date.setDate(date.getDate() - 1);
            FSDynamicProperty.setNumber(world, FSUtil.namespacedString("rateRequestDate"), date.getTime());
            FSDynamicProperty.setBoolean(world, FSUtil.namespacedString("hasSeenRateRequest"), false);
            world.sendMessage("§a[!] Rating test complete. Will prompt after: " + date.getTime());
        }
        if (eventData.id === "57d_sbunk:show_connection_log") {
            const player = eventData.sourceEntity;
            FormManager.sharedInstance().showConnectionLog(player);
        }
        if (eventData.id === "57d_sbunk:set_world_property" || eventData.id === "57d_sbunk:set_world_dynamic_property") {
            function parseMessage(message) {
                const regex = /(?:[^\s"]+|"[^"]*")+/g;
                const matches = message.match(regex);
                if (!matches) {
                    return [];
                }
                return matches.map(arg => arg.replace(/(^"|"$)/g, ""));
            }
            const data = parseMessage(eventData.message);
            if (data.length === 2) {
                let key = data[0];
                if (key.startsWith("ns:")) {
                    key = FSUtil.namespacedString(key.replace("ns:", ""));
                }
                else if (key.startsWith(":")) {
                    key = FSUtil.namespacedString(key.replace(":", ""));
                }
                var value = data[1];
                if (value === "true" || value === "false") {
                    value = value === "true";
                }
                world.setDynamicProperty(key, value);
                console.error(`[!] Set property ${key} to ${value}`);
            }
        }
        if (eventData.id === "57d_sbunk:get_world_property" || eventData.id === "57d_sbunk:get_world_dynamic_property") {
            console.log("Get prop");
            function parseMessage(message) {
                const regex = /(?:[^\s"]+|"[^"]*")+/g;
                const matches = message.match(regex);
                if (!matches) {
                    return [];
                }
                return matches.map(arg => arg.replace(/(^"|"$)/g, ""));
            }
            const data = parseMessage(eventData.message);
            if (data.length === 1) {
                let key = data[0];
                if (key.startsWith("ns:")) {
                    key = FSUtil.namespacedString(key.replace("ns:", ""));
                }
                else if (key.startsWith(":")) {
                    key = FSUtil.namespacedString(key.replace(":", ""));
                }
                const value = world.getDynamicProperty(key);
                console.error(`[!] Retrieved property ${key}: ${value}`);
            }
        }
    }
    handlePlayerInteract(eventData) {
        const entity = eventData.sourceEntity;
        const data = JSON.parse(eventData.message);
        const interaction = data.interaction;
        const callback_tag = `57d_sbunk:${interaction}__${entity.typeId}_callback`;
        const requires_admin_role = data.requires_admin_role;
        let tags = [];
        tags.push(callback_tag);
        if (requires_admin_role) {
            tags.push("fs_sbunk_is_admin");
        }
        const eqo_admin_player = {
            tags: tags,
            closest: 1,
            location: entity.location,
            maxDistance: 10
        };
        const players = entity.dimension.getPlayers(eqo_admin_player);
        const player = players.length > 0 ? players[0] : undefined;
        if (!player) {
            return;
        }
        player.removeTag(callback_tag);
        if (interaction === "player_did_interact_admin_allowed") {
            if (entity.typeId === "57d_sbunk:camera" && FSDynamicProperty.getBoolean(player, "is_camera")) {
                FormManager.sharedInstance().showExitCameraOptions(player);
            }
            else if (entity.typeId === "57d_sbunk:laser_floor" || entity.typeId === "57d_sbunk:laser_wall") {
                LaserBeam.outputLaserBeamRequiresLaserConsoleMessage(entity, player);
            }
            else if (entity.typeId === "57d_sbunk:camera" ||
                entity.typeId === "57d_sbunk:laser_console" ||
                entity.typeId === "57d_sbunk:security_turret" ||
                entity.typeId === "57d_sbunk:security_door" ||
                entity.typeId === "57d_sbunk:security_dog" ||
                entity.typeId === "57d_sbunk:elevator" ||
                entity.typeId === "57d_sbunk:elevator_placeable") {
                FSEntityPerms.showEntityPermissionMenu(player, entity);
            }
            else {
                FSEntityPerms.showEntityPermissionCustomizer(player, entity, true);
            }
        }
        if (interaction === "player_did_interact_admin_denied") {
            PlayerHelper.outputAdminAccessRequired(player);
            if (entity.typeId === "57d_sbunk:security_door") {
                SecurityDoor.onDeny(entity);
            }
        }
        if (interaction === "player_did_interact_allowed") {
            const entityTypeId = entity.typeId;
            if (entity.typeId === "57d_sbunk:security_door") {
                SecurityDoor.onInteract(entity);
            }
            if (entity.typeId === "57d_sbunk:laser_floor" || entity.typeId === "57d_sbunk:laser_wall") {
                LaserBeam.outputLaserBeamRequiresLaserConsoleMessage(entity, player);
            }
            if (entity.typeId === "57d_sbunk:camera") {
                CameraManager.outputUseTabletMessage(player);
            }
            if (entityTypeId.indexOf("57d_sbunk:secret_") !== -1) {
                SecretEntrance.onInteract(entity);
            }
            if (entityTypeId.indexOf("57d_sbunk:computer_monitor") !== -1) {
                ComputerMonitor.onInteract(entity, player);
            }
            if (entity.typeId === "57d_sbunk:laser_console") {
                EntranceManager.sharedInstance().consoleInteraction(entity, true);
            }
            if (entity.typeId === "57d_sbunk:locked_chest") {
                LockedBlock.onInteract(entity);
            }
            if (entity.typeId === "57d_sbunk:elevator" || entity.typeId === "57d_sbunk:elevator_placeable") {
                EntranceManager.sharedInstance().elevatorInteraction(entity);
            }
            if (entity.typeId.indexOf("57d_sbunk:entrance") > -1) {
                EntranceManager.sharedInstance().entranceInteraction(entity);
            }
            if (entity.typeId.indexOf("57d_sbunk:security_bot") > -1) {
                FormManager.sharedInstance().showSecurityBotOptions(entity, EntityManager.getClosestPlayer(entity));
            }
            if (entity.typeId.indexOf("57d_sbunk:training_bot") > -1) {
                FormManager.sharedInstance().showTrainingBotOptions(entity, EntityManager.getClosestPlayer(entity));
            }
        }
        if (interaction === "player_did_interact_denied") {
            let soundPlayed = false;
            if (entity.typeId === "57d_sbunk:camera") {
                CameraManager.outputUseTabletMessage(player);
                return;
            }
            if (entity.typeId === "57d_sbunk:security_door") {
                SecurityDoor.onDeny(entity);
            }
            if (entity.typeId.indexOf("57d_sbunk:secret_") !== -1) {
                SecretEntrance.onDeny(entity);
            }
            if (entity.typeId === "57d_sbunk:laser_console") {
                EntranceManager.sharedInstance().consoleInteraction(entity, false);
                soundPlayed = true;
            }
            if (entity.typeId === "57d_sbunk:elevator" || entity.typeId === "57d_sbunk:elevator_placeable") {
                EntranceManager.sharedInstance().elevatorDenied(entity);
            }
            if (entity.typeId === "57d_sbunk:locked_chest") {
                LockedBlock.onDeny(entity);
            }
            if (entity.typeId === "57d_sbunk:computer_monitor") {
                ComputerMonitor.onDeny(entity);
            }
            if (!FSEntityPerms.hasPlayerGotPermissionForEntity(players[0], entity, true)) {
                if (soundPlayed === false) {
                    world.playSound("fs.sbunk.access_denied", entity.location);
                }
            }
        }
    }
}

//# sourceMappingURL=../../../_SBUNK_BPDebug/fs_sbunk/ScriptEventManager.js.map
