import { system, world } from "@minecraft/server";
import FSPlayerPerms, { FSMessageType, FSPlayerAccessLevel, convertAccessLevelToColor, convertAccessLevelToName, getAllAccessLevels } from "./FSPlayerPerms";
import { PLAYER_PERMS_ALLOW_DELETE } from "../../FSConstants";
import FSUtil from "../../FSUtil";
import FSModalFormData from "../forms/ui/FSModalFormData";
import FSActionFormData from "../forms/ui/FSActionFormData";
import FSActionFormResponse from "../forms/resps/FSActionFormResp";
import FSFormManager from "../forms/FSFormManager";
import PlayerHelper from "../../../PlayerHelper";
import EntranceManager from "../../../EntranceManager";
import SecurityDoor from "../../../entity/SecurityDoor";
import EntityManager from "../../../EntityManager";
import FSLocalizedString from "../../FSLocalizedString";
import StructureManager from "../../../StructureManager";
import FSInventoryManager from "../FSInventoryManager";
import FSDynamicProperty from "../FSDynamicProperty";
import FSSoundManager from "../../FSSoundManager";
import FSWorldHelper from "../../FSWorldHelper";
const ENTITY_PERMISSION_STORAGE_KEY = FSUtil.namespacedString("player_access_levels");
export default class FSEntityPerms {
    static setEntityPermission(entity, permission) {
        entity.setDynamicProperty(ENTITY_PERMISSION_STORAGE_KEY, JSON.stringify([permission])); 
    }
    static getEntityPermission(entity) {
        const perms = entity.getDynamicProperty(ENTITY_PERMISSION_STORAGE_KEY);
        if (perms) {
            const parsedPerms = JSON.parse(perms);
            if (parsedPerms.length > 0) {
                return parsedPerms[0];
            }
        }
        return FSPlayerAccessLevel.Everyone; 
    }
    static clearEntityPermission(entity) {
        entity.setDynamicProperty(ENTITY_PERMISSION_STORAGE_KEY, JSON.stringify([]));
    }
    static setEntityCustomName(entity, customName = "") {
        if (customName.length === 0) {
            customName = "";
        }
        customName = customName.replace(/§./g, "");
        customName = customName.replace(/[^a-zA-Z0-9\.\-\_\,\$\&\s\']/g, "");
        customName = customName.replace(/§./g, "");
        if (customName.length > 128) {
            customName = customName.substr(0, 128);
        }
        if (entity.typeId.indexOf("57d_sbunk:elevator") !== -1 && customName.length === 0) {
            customName = "Untitled Floor";
        }
        if (customName.length === 0) {
            var entityType = "";
            try {
                entityType = entity.typeId.split(":")[1].toLowerCase();
            }
            catch (ex) { }
            customName = entityType.replace(/_/g, " ");
            customName = customName.replace(/\w\S*/g, txt => {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            });
        }
        entity.setDynamicProperty(FSUtil.namespacedString("custom_name"), customName);
    }
    static getEntityCustomName(entity, formatted = true, includeAccessLevel = true) {
        var customName = entity.getDynamicProperty(FSUtil.namespacedString("custom_name")) || "";
        if (customName.length > 24) {
            customName = customName.substr(0, 24);
        }
        const nameTruncated = customName + ""; 
        if (formatted) {
            const accessLevel = FSEntityPerms.getEntityPermission(entity);
            const formatting = convertAccessLevelToColor(accessLevel);
            customName = "§l" + formatting + customName;
            if (includeAccessLevel) {
                const accessLevelName = convertAccessLevelToName(accessLevel);
                customName = customName + "\n§r §7[" + formatting + accessLevelName + " Access§7] §r";
            }
            return customName;
        }
        return customName || "";
    }
    static hasPlayerGotPermissionForEntity(player, entity, sendErrorMessages = true) {
        return FSPlayerPerms.sharedInstance().hasAccessLevel(player, FSEntityPerms.getEntityPermission(entity), sendErrorMessages);
    }
    static showEntityPermissionMenu(sender, entity, userInfo = {}) {
        if (userInfo === undefined || userInfo === null) {
            userInfo = {};
        }
        if (!FSPlayerPerms.sharedInstance().isAdmin(sender)) {
            sender.sendMessage({
                translate: FSLocalizedString.localize("perms.no_permission", "§cYou do not have permission to edit permissions for this entity.", "Access denied error message")
            });
            return;
        }
        var formData = new FSActionFormData(FSUtil.namespacedString("entity_perms"), false);
        var name = FSUtil.truncateString(FSUtil.entityName(entity, true), 25, "...");
        formData.setTitle(name);
        if (entity.typeId === "57d_sbunk:laser_console") {
            formData.addButton("open_laser_door", {
                translate: FSLocalizedString.localize("ui.entity_permissions.open_laser_door.button", "Open Nearby Lasers", "Open laser door button")
            });
            formData.addButton("enable_nearby_lasers", {
                translate: FSLocalizedString.localize("ui.entity_permissions.enable_nearby_lasers.button", "Enable Nearby Lasers", "Enable nearby lasers button")
            });
            formData.addButton("disable_nearby_lasers", {
                translate: FSLocalizedString.localize("ui.entity_permissions.disable_nearby_lasers.button", "Disable Nearby Lasers", "Disable nearby lasers button")
            });
        }
        if (entity.typeId.indexOf("57d_sbunk:security_door") !== -1) {
            FSInventoryManager.replaceItemInHand(sender, "fs_sbunk:tablet_room", 1);
            FSWorldHelper.replaceTablets();
            const autoOpen = entity.getDynamicProperty(FSUtil.namespacedString("auto_open")) || false;
            if (!autoOpen) {
                formData.addButton("open_security_door", {
                    translate: FSLocalizedString.localize("ui.entity_permissions.open_security_door.button", "Open/Close Door", "Open/close security door button")
                });
            }
            if (FSDynamicProperty.getString(entity, "undo_id").length > 0) {
                formData.addButton("remove_room", {
                    translate: FSLocalizedString.localize("ui.entity_permissions.remove_room.button", "Remove Room", "Remove room button")
                });
            }
        }
        if (entity.typeId !== "57d_sbunk:elevator" && entity.typeId !== "57d_sbunk:elevator_placeable") {
            formData.addButton("edit_permissions", {
                translate: FSLocalizedString.localize("ui.entity_permissions.edit_permissions.button", "Edit Permissions", "Edit permissions button")
            });
        }
        else {
            formData.addButton("open_elevator_doors", {
                translate: FSLocalizedString.localize("ui.entity_permissions.open_elevator_doors.button", "Open/Close Elevator Doors", "Open/close elevator doors button")
            });
            formData.addButton("edit_permissions", {
                translate: FSLocalizedString.localize("ui.entity_permissions.edit_floor.button", "Edit Floor", "Edit floor button")
            });
        }
        let canDelete = false;
        PLAYER_PERMS_ALLOW_DELETE.forEach(type => {
            if (entity.typeId.indexOf(type) !== -1) {
                canDelete = true;
            }
        });
        if (entity.typeId.indexOf("57d_sbunk:camera") !== -1) {
            formData.addButton("view_camera", {
                translate: FSLocalizedString.localize("ui.entity_permissions.view_camera.button", "View Camera", "View camera button")
            });
        }
        if (entity.typeId.indexOf("57d_sbunk:camera") !== -1) {
            formData.addButton("teleport_camera", {
                translate: FSLocalizedString.localize("ui.entity_permissions.teleport_camera.button", "Teleport to Camera", "Teleport to camera button")
            });
        }
        if (canDelete) {
            const rawText = {
                rawtext: [
                    {
                        text: "§c"
                    },
                    {
                        translate: FSLocalizedString.localize("ui.entity_permissions.delete_entity.button", "Remove %s", "Remove entity button. Please do not remove the %s token."),
                        with: [FSUtil.truncateString(FSUtil.entityName(entity, true), 16)]
                    }
                ]
            };
            formData.addButton("delete_entity", rawText);
        }
        formData.addButton("cancel", FSLocalizedString.localize("ui.entity_permissions.cancel.button.1", "Cancel", "Cancel button"));
        formData.push(sender, false, response => {
            FSInventoryManager.replaceItemInHand(sender, "fs_sbunk:tablet", 1);
            FSWorldHelper.replaceTablets();
            if (!response.canceled) {
                const resp = response;
                const buttons = resp.data;
                if (buttons["edit_permissions"]) {
                    this.showEntityPermissionCustomizer(sender, entity);
                }
                else if (buttons["delete_entity"]) {
                    this.showEntityRemoveConfirmation(sender, entity);
                }
                else if (buttons["teleport_camera"]) {
                    resp.finish();
                    FSFormManager.sharedInstance().navigationControllerForPlayer(sender).clear();
                    const cameraPermission = FSEntityPerms.getEntityPermission(entity);
                    if (!FSPlayerPerms.sharedInstance().hasAccessLevel(sender, cameraPermission)) {
                        sender.sendMessage({
                            translate: FSLocalizedString.localize("perms.no_permission.teleport_camera", "§cYou do not have permission to teleport this camera. You need %s access.", "Access denied error message, the %s is the name of the access level required."),
                            with: [convertAccessLevelToName(cameraPermission)]
                        });
                        return;
                    }
                    const didSeeTabletTip = sender.getDynamicProperty(FSUtil.namespacedString("did_see_tablet_tip"));
                    if (!didSeeTabletTip) {
                        sender.sendMessage({
                            translate: FSLocalizedString.localize("ui.entity_permissions.tablet_tip.1", "§e[Tip] You can also access your cameras with your Security Tablet!", "Tablet tip message")
                        });
                        sender.setDynamicProperty(FSUtil.namespacedString("did_see_tablet_tip"), true);
                    }
                    PlayerHelper.confirmTeleportToCameraWithId(sender, entity.id);
                }
                else if (buttons["view_camera"]) {
                    resp.finish();
                    FSFormManager.sharedInstance().navigationControllerForPlayer(sender).clear();
                    const cameraPermission = FSEntityPerms.getEntityPermission(entity);
                    if (!FSPlayerPerms.sharedInstance().hasAccessLevel(sender, cameraPermission)) {
                        sender.sendMessage({
                            translate: FSLocalizedString.localize("perms.no_permission.view_camera", "§cYou do not have permission to view this camera. You need %s access.", "Access denied error message, the %s is the name of the access level required."),
                            with: [convertAccessLevelToName(cameraPermission)]
                        });
                        return;
                    }
                    const didSeeTabletTip = sender.getDynamicProperty(FSUtil.namespacedString("did_see_tablet_tip"));
                    if (!didSeeTabletTip) {
                        sender.sendMessage({
                            translate: FSLocalizedString.localize("ui.entity_permissions.tablet_tip.2", "§e[Tip] You can also access your cameras with your Security Tablet!", "Tablet tip message")
                        });
                        sender.setDynamicProperty(FSUtil.namespacedString("did_see_tablet_tip"), true);
                    }
                    PlayerHelper.becomeCameraWithId(sender, entity.id);
                }
                else if (buttons["open_laser_door"]) {
                    if (entity.typeId === "57d_sbunk:laser_console") {
                        const isAllowed = FSEntityPerms.hasPlayerGotPermissionForEntity(sender, entity, true);
                        EntranceManager.sharedInstance().consoleInteraction(entity, isAllowed);
                        resp.finish();
                    }
                }
                else if (buttons["enable_nearby_lasers"]) {
                    if (entity.typeId === "57d_sbunk:laser_console") {
                        const isAllowed = FSEntityPerms.hasPlayerGotPermissionForEntity(sender, entity, true);
                        EntranceManager.sharedInstance().consoleEnableNearbyLasers(entity, isAllowed);
                        resp.finish();
                    }
                }
                else if (buttons["disable_nearby_lasers"]) {
                    if (entity.typeId === "57d_sbunk:laser_console") {
                        const isAllowed = FSEntityPerms.hasPlayerGotPermissionForEntity(sender, entity, true);
                        EntranceManager.sharedInstance().consoleDisableNearbyLasers(entity, isAllowed);
                        resp.finish();
                    }
                }
                else if (buttons["open_security_door"]) {
                    if (entity.typeId.indexOf("57d_sbunk:security_door") !== -1) {
                        const isAllowed = FSEntityPerms.hasPlayerGotPermissionForEntity(sender, entity, true);
                        if (isAllowed) {
                            SecurityDoor.onInteract(entity);
                        }
                        else {
                            world.playSound("fs.sbunk.access_denied", entity.location);
                        }
                        resp.finish();
                    }
                }
                else if (buttons["remove_room"]) {
                    if (entity.typeId.indexOf("57d_sbunk:security_door") !== -1) {
                        this.showRoomRemoveConfirmation(sender, entity);
                        resp.finish();
                    }
                }
                else if (buttons["open_elevator_doors"]) {
                    if (entity.typeId.indexOf("57d_sbunk:elevator") !== -1) {
                        EntranceManager.sharedInstance().elevatorInteraction(entity);
                        resp.finish();
                    }
                }
            }
        });
    }
    static showRoomRemoveConfirmation(sender, entity) {
        const undo_id = FSDynamicProperty.getString(entity, "undo_id");
        const form = new FSActionFormData("remove_room", false);
        form.setTitle(FSLocalizedString.localize("ui.remove_room.title", "Confirm Room Removal", "Confirm Room Removal Title."));
        form.setBody(FSLocalizedString.localize("ui.remove_room.body", "Are you sure you want to remove this room?", "Ask the player if they are sure they want to remove the room."));
        form.addButton("undo", FSLocalizedString.localize("ui.remove_room.button.undo", "Yes, remove the room!", "Button to remove the room"), "textures/57digital/sbunk/icons/undo.png");
        form.addButton("cancel", FSLocalizedString.localize("ui.remove_room.button.cancel", "Cancel", "Button to cancel"));
        sender.playSound("random.pop");
        form.push(sender, false, resp => {
            if (resp.canceled) {
                return;
            }
            if (resp instanceof FSActionFormResponse) {
                const response = resp;
                const formResponseData = response.getResponseData();
                if (formResponseData["undo"]) {
                    StructureManager.Undo(sender, undo_id);
                }
            }
        });
    }
    static showEntityRemoveConfirmation(sender, entity) {
        if (!FSPlayerPerms.sharedInstance().isAdmin(sender)) {
            sender.sendMessage({
                translate: FSLocalizedString.localize("perms.no_permission.remove_entity", "§cYou do not have permission to edit permissions for this entity.", "Access denied error message")
            });
            return;
        }
        var formData = new FSActionFormData(FSUtil.namespacedString("entity_remove_confirmation"), false);
        var name = FSUtil.entityName(entity, true);
        formData.setTitle(name); 
        formData.setBody({
            translate: FSLocalizedString.localize("ui.entity_permissions.remove_confirmation.body", "Are you sure you want to remove %s? This action cannot be undone.", "Remove entity confirmation message. The %s token is the name of the entity to be removed."),
            with: [name]
        });
        let rawtext = {
            rawtext: [
                {
                    text: "§c"
                },
                {
                    translate: FSLocalizedString.localize("ui.entity_permissions.remove_confirmation.confirm", "Remove %s", "Remove entity confirmation button. The %s token is the name of the entity to be removed."),
                    with: [name]
                }
            ]
        };
        formData.addButton("confirm", rawtext);
        formData.addButton("cancel", {
            translate: FSLocalizedString.localize("ui.entity_permissions.cancel.button.2", "Cancel", "Cancel button")
        });
        formData.push(sender, false, response => {
            if (!response.canceled) {
                const resp = response;
                const buttons = resp.data;
                if (buttons["confirm"]) {
                    let coords = entity.location.x.toFixed(0) + ", " + entity.location.y.toFixed(0) + ", " + entity.location.z.toFixed(0);
                    let entityName = entity.nameTag;
                    if (entityName.length > 0) {
                        entityName.replace(/\n/g, " ");
                    }
                    entityName.trimEnd();
                    entityName = entityName.replace(/\n/g, " ");
                    if (entityName.length > 0) {
                        FSPlayerPerms.sharedInstance().forceSendMessageToAllAdmins({
                            translate: FSLocalizedString.localize("perms.remove_entity.alert", "§c[§lSecurity Alert§r§c] %s removed %s at §c(%s).", "E.g: §c[§lSecurity Alert§r§c] ENDER_HUNTER2 removed Security Door §c(100, 200, 300). Security alert message. The %s tokens are the name of the player who removed the entity, the name of the entity removed, and the coordinates of the entity."),
                            with: [sender.name, entityName, coords]
                        });
                    }
                    else {
                        FSPlayerPerms.sharedInstance().forceSendMessageToAllAdmins({
                            translate: FSLocalizedString.localize("perms.remove_entity.alert.unknown_entity", "§c[§lSecurity Alert§r§c] %s removed an entity at §c(%s).", "E.g: §c[§lSecurity Alert§r§c] ENDER_HUNTER2 removed an entity at §c(100, 200, 300). Security alert message. The %s tokens are the name of the player who removed the entity, and the coordinates of the entity."),
                            with: [sender.name, coords]
                        });
                    }
                    try {
                        entity.triggerEvent("fs:pop_to_item");
                    }
                    catch (error) { }
                    system.runTimeout(() => {
                        if (entity.isValid()) {
                            entity.remove();
                        }
                    }, 1);
                }
                else {
                    this.showEntityPermissionMenu(sender, entity);
                }
                resp.finish();
            }
        });
    }
    static accessLevelName(accessLevel, formatted = false) {
        if (formatted) {
            return `${convertAccessLevelToColor(accessLevel)}${convertAccessLevelToName(accessLevel)}§r`;
        }
        return convertAccessLevelToName(accessLevel);
    }
    static showEntityPermissionCustomizer(sender, entity, resetNavStack = false) {
        if (!FSPlayerPerms.sharedInstance().isAdmin(sender)) {
            sender.sendMessage({
                translate: FSLocalizedString.localize("perms.no_permission.edit_permissions", "§cYou do not have permission to edit permissions for this entity.", "Access denied error message")
            });
            return;
        }
        FSInventoryManager.replaceItemInHand(sender, "fs_sbunk:tablet_settings", 1);
        FSWorldHelper.replaceTablets();
        if (resetNavStack) {
            FSFormManager.sharedInstance().navigationControllerForPlayer(sender).clear();
        }
        const perms = FSEntityPerms.getEntityPermission(entity);
        var existingPermissionIndex = 0;
        var type = entity.typeId.split(":")[1];
        type = type.replace(/_/g, " ");
        var accessLevels = ["permission.everyone", "permission.red", "permission.orange", "permission.yellow", "permission.green", "permission.blue", "permission.pink"];
        existingPermissionIndex = accessLevels.indexOf(perms);
        var formData = new FSModalFormData("57d:entity_perms", false);
        if (entity.typeId.indexOf("elevator") === -1) {
            formData.setTitle({
                translate: FSLocalizedString.localize("ui.entity_permissions.entity_perms.title", "Entity Permissions", "entity permissions title")
            });
        }
        else {
            formData.setTitle({
                translate: FSLocalizedString.localize("ui.entity_permissions.floor_customize.title", "Floor Customization", "floor customization title")
            });
        }
        let customNameLabel = {
            translate: FSLocalizedString.localize("ui.entity_permissions.custom_name.label", "Custom Name:", "Custom name label")
        };
        if (entity.typeId.indexOf("57d_sbunk:elevator") !== -1) {
            customNameLabel = {
                translate: FSLocalizedString.localize("ui.entity_permissions.floor_name.label", "Floor Name:", "Floor name label")
            };
        }
        if (entity.typeId.indexOf("chest") !== -1) {
            customNameLabel = {
                rawtext: [
                    { text: "§b[TIP] To open a locked chest, just interact with the chest when NOT holding your Security Tablet." },
                    {
                        text: "\n\n§r"
                    },
                    { translate: FSLocalizedString.localize("ui.entity_permissions.chest_name.label", "Chest Name:", "Chest name label") }
                ]
            };
        }
        if (entity.typeId.indexOf("57d_sbunk:entrance") !== -1) {
            customNameLabel = {
                rawtext: [
                    { text: "§b[!] " },
                    { translate: FSLocalizedString.localize("ui.entity_permissions.entrance_perms.tip", "TIP: To open this entrance, interact with the entrance without holding your tablet.", "Entrance permissions access tip") },
                    {
                        text: "\n\n§r"
                    },
                    { translate: FSLocalizedString.localize("ui.entity_permissions.entrance_name2.label", "Entrance Name:", "Entrance name label") }
                ]
            };
        }
        const optionalValueLabel = {
            translate: FSLocalizedString.localize("ui.entity_permissions.optional.label", "Optional", "Text field default text, should read Optional in the UI")
        };
        const customNameValue = entity.getDynamicProperty(FSUtil.namespacedString("custom_name")) || "";
        formData.addTextField("custom_name", customNameLabel, optionalValueLabel, customNameValue, false);
        if (entity.typeId.indexOf("57d_sbunk:elevator") !== -1) {
            const entryMessage = FSDynamicProperty.getString(entity, FSUtil.namespacedString("entry_message"));
            const rawtext = {
                rawtext: [
                    {
                        translate: FSLocalizedString.localize("ui.entity_permissions.entry_message.label", "Entry Message:", "Entry message label. The entry message is a small welcome message when the player arrives in the bunker.")
                    },
                    {
                        text: "\n§8"
                    },
                    {
                        translate: FSLocalizedString.localize("ui.entity_permissions.entry_message.label_tip", "Send a message to players when they arrive on this floor.", "A tip about what the entry message means.")
                    }
                ]
            };
            formData.addTextField("entry_message", rawtext, optionalValueLabel, entryMessage, false);
            const sound = FSDynamicProperty.getNumber(entity, FSUtil.namespacedString("sound")) || 0;
            const soundDisplayNames = [
                "None",
                "Welcome (male)",
                "Welcome (female)",
                "Welcome (robot)",
                "Access Granted",
                "Evil Laugh",
                "Hummous",
                "Happy Birthday!",
                "Ground Floor",
                "Floor 1",
                "Floor 2",
                "Floor 3",
                "Floor 4",
                "Floor 5",
                "Respect the rules!",
                "Keep Out Song",
                "Go Away Song",
                "Welcome to This Floor Song",
                "Annoying Song",
                "Welcome LOL Song",
                "Wololo",
                "Burp",
                "Baa"
            ];
            formData.addDropdown("sound", {
                translate: FSLocalizedString.localize("ui.entity_permissions.sound.label", "Entry Sound:", "Sound label")
            }, soundDisplayNames, sound);
        }
        var disableDropdown = false;
        if (entity.typeId === "57d_sbunk:elevator") {
            disableDropdown = true;
        }
        var everyoneOptionText = {
            translate: FSLocalizedString.localize("ui.entity_permissions.permission.everyone", "Everyone", "Everyone label")
        };
        var titlePermissionField = {
            translate: FSLocalizedString.localize("ui.entity_permissions.permission.label", "Permission to Use:", "Permission label")
        };
        if (entity.typeId.indexOf("dog") !== -1 || entity.typeId.indexOf("turret") !== -1) {
            titlePermissionField = {
                translate: FSLocalizedString.localize("ui.entity_permissions.do_not_attack.label", "Do Not Atack:", "Do Not Attack label")
            };
            everyoneOptionText = {
                translate: FSLocalizedString.localize("ui.entity_permissions.permission.anyone", "Anyone", "Anyone label")
            };
        }
        if (!disableDropdown) {
            formData.addDropdown("permission", titlePermissionField, [
                everyoneOptionText,
                {
                    rawtext: [
                        { text: "§c" },
                        {
                            translate: FSLocalizedString.localize("permission.red", "Red", "Red label")
                        }
                    ]
                },
                {
                    rawtext: [
                        { text: "§6" },
                        {
                            translate: FSLocalizedString.localize("permission.orange", "Orange", "Orange label")
                        }
                    ]
                },
                {
                    rawtext: [
                        { text: "§e" },
                        {
                            translate: FSLocalizedString.localize("permission.yellow", "Yellow", "Yellow label")
                        }
                    ]
                },
                {
                    rawtext: [
                        { text: "§a" },
                        {
                            translate: FSLocalizedString.localize("permission.green", "Green", "Green label")
                        }
                    ]
                },
                {
                    rawtext: [
                        { text: "§b" },
                        {
                            translate: FSLocalizedString.localize("permission.blue", "Blue", "Blue label")
                        }
                    ]
                },
                {
                    rawtext: [
                        { text: "§d" },
                        {
                            translate: FSLocalizedString.localize("permission.pink", "Pink", "Pink label")
                        }
                    ]
                }
            ], existingPermissionIndex);
        }
        if (entity.typeId.indexOf("57d_sbunk:security_door") !== -1) {
            const autoOpen = entity.getDynamicProperty(FSUtil.namespacedString("auto_open")) || false;
            formData.addToggle("auto_open", {
                translate: FSLocalizedString.localize("ui.entity_permissions.auto_open.label", "Auto-Open Door", "Auto-open door label")
            }, autoOpen);
        }
        if (entity.typeId.indexOf("dog") !== -1 || entity.typeId.indexOf("turret") !== -1) {
            const attackPlayers = entity.getDynamicProperty(FSUtil.namespacedString("attack_players")) || false;
            formData.addToggle("attack_players", {
                translate: FSLocalizedString.localize("ui.entity_permissions.attack_players.label", "Attack Players", "Attack players label")
            }, attackPlayers);
        }
        if (entity.typeId.indexOf("dog") !== -1 || entity.typeId.indexOf("turret") !== -1) {
            const attackMobs = entity.getDynamicProperty(FSUtil.namespacedString("attack_mobs")) || false;
            var attackLabel = {
                rawtext: [{ translate: FSLocalizedString.localize("ui.entity_permissions.attack_mobs.label", "Attack Mobs", "Attack mobs label") }]
            };
            if (entity.typeId.indexOf("dog") !== -1) {
                attackLabel.rawtext.push({ text: "\n\n§a" });
                attackLabel.rawtext.push({ translate: FSLocalizedString.localize("ui.entity_permissions.attack_mobs.tip", "Tip! Feed your Guard Dog lots of bones to make them follow you around!", "Attack mobs tip") });
            }
            formData.addToggle("attack_mobs", attackLabel, attackMobs);
        }
        if (entity.typeId.indexOf("57d_sbunk:camera") !== -1) {
            const sendNotifications = entity.getDynamicProperty(FSUtil.namespacedString("send_notifications")) || false;
            formData.addToggle("send_notifications", { translate: FSLocalizedString.localize("ui.entity_permissions.send_notifications.label", "Send Movement Notifications", "Send notifications when detected a player moving") }, sendNotifications);
        }
        formData.push(sender, false, response => {
            FSInventoryManager.replaceItemInHand(sender, "fs_sbunk:tablet", 1);
            FSWorldHelper.replaceTablets();
            if (!response.canceled) {
                const resp = response;
                const permissionIndex = resp.data.permission;
                const accessLevelIndex = FSPlayerPerms.sharedInstance().getAccessLevelFromNumber(permissionIndex);
                this.setEntityPermission(entity, accessLevelIndex);
                this.setEntityCustomName(entity, resp.data.custom_name || "");
                if (entity.typeId.indexOf("57d_sbunk:security_door") !== -1) {
                    const autoOpen = resp.data.auto_open || false;
                    entity.setDynamicProperty(FSUtil.namespacedString("auto_open"), autoOpen);
                    if (autoOpen) {
                        try {
                            entity.addTag(FSUtil.namespacedString("auto_open"));
                        }
                        catch (ex) { }
                    }
                    else {
                        try {
                            entity.removeTag(FSUtil.namespacedString("auto_open"));
                        }
                        catch (ex) { }
                    }
                }
                if (entity.typeId.indexOf("dog") !== -1 || entity.typeId.indexOf("turret") !== -1) {
                    const attackPlayers = resp.data.attack_players || false;
                    entity.setDynamicProperty(FSUtil.namespacedString("attack_players"), attackPlayers);
                    if (attackPlayers) {
                        try {
                            entity.addTag(FSUtil.namespacedString("attack_players"));
                        }
                        catch (ex) { }
                    }
                    else {
                        try {
                            entity.removeTag(FSUtil.namespacedString("attack_players"));
                        }
                        catch (ex) { }
                    }
                    const attackMobs = resp.data.attack_mobs || false;
                    entity.setDynamicProperty(FSUtil.namespacedString("attack_mobs"), attackMobs);
                    if (attackMobs) {
                        try {
                            entity.addTag(FSUtil.namespacedString("attack_mobs"));
                        }
                        catch (ex) { }
                    }
                    else {
                        try {
                            entity.removeTag(FSUtil.namespacedString("attack_mobs"));
                        }
                        catch (ex) { }
                    }
                    try {
                        entity.removeTag(FSUtil.namespacedString("permission.everyone"));
                        entity.removeTag(FSUtil.namespacedString("permission.red"));
                        entity.removeTag(FSUtil.namespacedString("permission.orange"));
                        entity.removeTag(FSUtil.namespacedString("permission.yellow"));
                        entity.removeTag(FSUtil.namespacedString("permission.green"));
                        entity.removeTag(FSUtil.namespacedString("permission.blue"));
                        entity.removeTag(FSUtil.namespacedString("permission.pink"));
                    }
                    catch (ex) {
                        console.error("Error removing tags: " + ex);
                    }
                    var colorTag = getAllAccessLevels()[permissionIndex].toLowerCase();
                    try {
                        entity.addTag(FSUtil.namespacedString(colorTag));
                    }
                    catch (ex) { }
                }
                if (entity.typeId.indexOf("57d_sbunk:camera") !== -1) {
                    const sendNotifications = resp.data.send_notifications || false;
                    entity.setDynamicProperty(FSUtil.namespacedString("send_notifications"), sendNotifications);
                    try {
                        entity.removeTag(FSUtil.namespacedString("send_notifications"));
                    }
                    catch (ex) { }
                    if (sendNotifications) {
                        try {
                            entity.addTag(FSUtil.namespacedString("send_notifications"));
                        }
                        catch (ex) { }
                    }
                }
                if (entity.typeId.indexOf("57d_sbunk:elevator") !== -1) {
                    FSDynamicProperty.setString(entity, FSUtil.namespacedString("entry_message"), FSUtil.truncateString(FSUtil.stripFormatting(resp.data.entry_message), 256) || "");
                    const sound = resp.data.sound || 0;
                    FSDynamicProperty.setNumber(entity, FSUtil.namespacedString("sound"), sound);
                    FSSoundManager.playElevatorSound(entity, sound);
                }
                const customName = this.getEntityCustomName(entity);
                if (entity.typeId.indexOf("57d_sbunk:secret_") === -1 && entity.typeId.indexOf("57d_sbunk:entrance_") === -1) {
                    entity.nameTag = customName;
                }
                let showPermsNameTag = true;
                if (entity.typeId === "57d_sbunk:elevator") {
                    showPermsNameTag = false;
                }
                if (entity.typeId.indexOf("57d_sbunk:secret_") === -1 && entity.typeId.indexOf("57d_sbunk:entrance_") === -1) {
                    entity.nameTag = FSEntityPerms.getEntityCustomName(entity, true, showPermsNameTag);
                }
                EntityManager.entityPermissionDidChange(entity);
                if (entity.typeId.indexOf("camera") !== -1) {
                }
                else if (entity.typeId.indexOf("elevator") === -1) {
                }
                else {
                    const didSeeTabletTip = FSDynamicProperty.getBoolean(world, FSUtil.namespacedString("did_see_tablet_tip")) || false;
                    if (!didSeeTabletTip) {
                        sender.sendMessage({ translate: FSLocalizedString.localize("ui.entity_permissions.tablet_tip.3", "§e[Tip] To open elevators and doors, just interact with them - you do not need to hold the Security Tablet.", "Tablet tip message") });
                        FSDynamicProperty.setBoolean(world, FSUtil.namespacedString("did_see_tablet_tip"), true);
                    }
                }
                resp.finish();
            }
            else {
                if (!resetNavStack) {
                }
            }
        });
    }
    static sendPlayerAlertForMatchingEntityPermissions(entity, message = "", type = FSMessageType.Message) {
        if (entity) {
            const permissionLevel = FSEntityPerms.getEntityPermission(entity);
            message = message.replace(/<entity_name>/g, FSEntityPerms.getEntityCustomName(entity, true, true)).replace(/\n/g, " ");
            FSPlayerPerms.sharedInstance().sendMessageToPermissionLevel(message, permissionLevel, type);
        }
    }
}

//# sourceMappingURL=../../../../../../_SBUNK_BPDebug/fs_sbunk/fs/libs/perms/FSEntityPerms.js.map
