import { Block, Entity, EntityComponentTypes, EquipmentSlot, ItemStack, Player, system, VanillaEntityIdentifier, world } from "@minecraft/server";
import { applyDamage } from "../../types/function";
import { ActionFormData, ActionFormResponse, ModalFormData, ModalFormResponse } from "@minecraft/server-ui";
import { wrap } from "module";
/**
 * 锁效果：
 * 
 */
// system.run(() => {
//     const player = world.getAllPlayers()[0];
//     world.clearDynamicProperties()

// })

system.beforeEvents.startup.subscribe((init) => {
    init.itemComponentRegistry.registerCustomComponent('xxr:lock', {
        onHitEntity: (event) => {
            // 注册占位
        }
    })
})



world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
    const player = event.player;
    const block = event.block;
    if (!event.isFirstEvent) return;
    const item = player.getComponent(EntityComponentTypes.Equippable)?.getEquipment(EquipmentSlot.Mainhand);
    if (world.getDynamicProperty(`lockPassword:${block.location.x},${block.location.y},${block.location.z},${block.dimension.id}`)) {
        const lockValue = world.getDynamicProperty(`lockPassword:${block.location.x},${block.location.y},${block.location.z},${block.dimension.id}`) as string || '{}';
        if (lockValue !== '{}') {
            const lockPassword = JSON.parse(lockValue) as LockPassword;
            if (!lockPassword.believer.includes(player.id)) {
                event.cancel = true;
                player.sendMessage('你不是这个箱子的所有者');
            } else {
                if (!item?.getComponent('xxr:lock')) return;

                // 检查是否为箱子,同时玩家是蹲下
                const container = block.getComponent('inventory')?.container;
                if (!container && player.isSneaking) return;
                system.run(() => {
                    setLock(block, player, item.typeId);
                    console.log('方块位置:', block.location.x, block.location.y, block.location.z);
                    console.log('方块ID: ', block.typeId);

                })
            }
        }
    }

})


const passwordNumber = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
interface LockPassword {
    pos: {
        x: number,
        y: number,
        z: number,
        dimension: string,
    },
    password: string,
    believer: string[]
    lockType: string
}
function setLock(block: Block, player: Player, lockType: string): void {
    try {
        console.log(world.getDynamicProperty(`lockPassword:${block.location.x},${block.location.y},${block.location.z},${block.dimension.id}`));
    } catch (error) {
        console.log(error);
    }
    const defaultLockPassword = world.getDynamicProperty(`lockPassword:${block.location.x},${block.location.y},${block.location.z},${block.dimension.id}`) as string || '{}';
    let value: LockPassword;
    if (defaultLockPassword !== '{}') {
        value = JSON.parse(defaultLockPassword) as LockPassword;
    } else {
        value = {
            pos: {
                x: block.location.x,
                y: block.location.y,
                z: block.location.z,
                dimension: block.dimension.id,
            },
            password: '',
            believer: [],
            lockType: lockType
        }
    }

    // 提取现有密码的每一位
    const existingPassword = value.password || '';
    const passwordDigits = existingPassword.split('');

    const ui = new ModalFormData();
    ui.title('设置锁')
        .label('请输入密码')
        .dropdown('第一位', passwordNumber, {
            defaultValueIndex: Math.max(0, passwordNumber.indexOf(passwordDigits[0] || '0'))
        })
        .dropdown('第二位', passwordNumber, {
            defaultValueIndex: Math.max(0, passwordNumber.indexOf(passwordDigits[1] || '0'))
        })
        .dropdown('第三位', passwordNumber, {
            defaultValueIndex: Math.max(0, passwordNumber.indexOf(passwordDigits[2] || '0'))
        })
        .dropdown('第四位', passwordNumber, {
            defaultValueIndex: Math.max(0, passwordNumber.indexOf(passwordDigits[3] || '0'))
        })
        .dropdown('第五位', passwordNumber, {
            defaultValueIndex: Math.max(0, passwordNumber.indexOf(passwordDigits[4] || '0'))
        })
        .dropdown('第六位', passwordNumber, {
            defaultValueIndex: Math.max(0, passwordNumber.indexOf(passwordDigits[5] || '0'))
        })
        .submitButton('设置')
        .show(player)
        .then((response: ModalFormResponse) => {
            if (!response.formValues) return;
            // 保存密码逻辑
            const password = response.formValues.map((value) => value as string).join('');
            if (world.getDynamicProperty(`lockPassword:${block.location.x},${block.location.y},${block.location.z},${block.dimension.id}`)) {
                world.setDynamicProperty(`lockPassword:${block.location.x},${block.location.y},${block.location.z},${block.dimension.id}`, JSON.stringify({
                    pos: {
                        x: block.location.x,
                        y: block.location.y,
                        z: block.location.z,
                        dimension: block.dimension.id,
                    },
                    password: password,
                    believer: value.believer,
                    lockType: lockType
                }));
                player.sendMessage(`新的密码为${password}`);
            } else {
                world.setDynamicProperty(`lockPassword:${block.location.x},${block.location.y},${block.location.z},${block.dimension.id}`, JSON.stringify({
                    pos: {
                        x: block.location.x,
                        y: block.location.y,
                        z: block.location.z,
                        dimension: block.dimension.id,
                    },
                    password: password,
                    believer: ['123'],
                    lockType: lockType
                }));
                player.sendMessage(`锁密码已设置为${password}`);
            }
        })
}


