import { world, system, ItemStack, EntityComponentTypes, BlockVolume } from "@minecraft/server";

export const dimensions = ["overworld", "nether", "the_end"];


const memoryGameWaitTime = 50;

let debugCurItemIndex = 0;

// 事件监听
system.afterEvents.scriptEventReceive.subscribe((event) => {
    const { id, message, sourceEntity } = event;

    // 传送技能
    if (id === 'pm_mock:the_snatching_teleport') {
        teleportSkill(sourceEntity);
    }

    // 切换到游戏模式4
    else if (id === 'pm_mock:the_snatching_skill_4') {
        handleSkill4(sourceEntity);
    }

    // 游戏模式4，切换物品
    else if (id === 'pm_mock:the_snatching_skill_4_switch') {
        handleSkill4Switch(sourceEntity);
    }

    // 游戏模式4，确认物品索引是否为0
    else if (id === 'pm_mock:the_snatching_skill_4_confirm') {
        handleSkill4Confirm(sourceEntity);
    }

    // 偷玩家物品
    else if (id === 'pm_mock:the_snatching_skill_2_steal') {
        stealPlayerItem(sourceEntity);
    }

    // 检查周围有没有紫颂植物
    else if (id === 'pm_mock:the_snatching_check_chorus') {
        checkForChorusPlant(sourceEntity);
    }

    // 切换到模式6：交换
    else if (id === 'pm_mock:the_snatching_skill_6') {
        handleSkill6(sourceEntity);
    }

    // 模式6，成功交换
    else if (id === 'pm_mock:the_snatching_skill_6_exchanged') {
        handleSkill6Success(sourceEntity);
    }

});

// 模式6
function handleSkill6(sourceEntity) {
    const players = sourceEntity.dimension.getPlayers({ location: sourceEntity.location, maxDistance: 30 });
    players.forEach((player) => {
        player.onScreenDisplay.setActionBar({ text: 'If you want your item back, \nexchange it with a §eChorus Fruit§f!'})
    });
}

// 模式6，成功交换
function handleSkill6Success(sourceEntity) {
    const players = sourceEntity.dimension.getPlayers({ location: sourceEntity.location, maxDistance: 10 });
    players.forEach((player) => {
        player.onScreenDisplay.setActionBar({ text: 'Here you go!'});
    });
    // 掉落之前偷的物品
    // 获取实体物品栏0号位的物品
    const inventoryComponent = sourceEntity.getComponent('minecraft:inventory');
    if (inventoryComponent) {
        const container = inventoryComponent.container;
        const itemInSlot = container.getItem(0);

        if (itemInSlot) {
            const itemName = itemInSlot.typeId;

            // 使用loot指令掉落物品
            sourceEntity.runCommand(`loot spawn ~~~ loot "snatch_table/snatch_${itemName.split(':')[1]}"`);

            // 清空实体物品栏0号位
            container.setItem(0, null);
            sourceEntity.setProperty('pm_mock:item_carryed_state', 0);

            // 重置回默认
            sourceEntity.triggerEvent("skill_3");
        }
    }

}

//所有能偷的
const itemsCanSnatch = [
    // 食物
    "apple",
    "baked_potato",
    "beetroot",
    "beetroot_soup",
    "bread",
    "cake",
    "carrot",
    "chorus_fruit",
    "cooked_beef",
    "cooked_chicken",
    "cooked_cod",
    "cooked_mutton",
    "cooked_porkchop",
    "cooked_rabbit",
    "cooked_salmon",
    "cookie",
    "dried_kelp",
    "dried_kelp_block",
    "enchanted_golden_apple",
    "golden_apple",
    "golden_carrot",
    "honey_bottle",
    "melon_slice",
    "mushroom_stew",
    "poisonous_potato",
    "potato",
    "pufferfish",
    "pumpkin_pie",
    "rabbit_stew",
    "beef",
    "chicken",
    "cod",
    "mutton",
    "porkchop",
    "rabbit",
    "salmon",
    "rotten_flesh",
    "spider_eye",
    "cooked_beef",
    "suspicious_stew",
    "sweet_berries",
    "tropical_fish",
    "glow_berries",

    // 矿石
    "copper_ingot",
    "gold_ingot",
    "iron_ingot",
    "netherite_ingot",
    "amethyst_shard",
    "diamond",
    "emerald",
    "lapis_lazuli",
    "quartz",

    //建筑方块
    "oak_planks",
    "oak_log",
    "oak_wood",
    "acacia_planks",
    "acacia_log",
    "acacia_wood",
    "birch_planks",
    "birch_log",
    "birch_wood",
    "dark_oak_planks",
    "dark_oak_log",
    "dark_oak_wood",
    "jungle_planks",
    "jungle_log",
    "jungle_wood",
    "spruce_planks",
    "spruce_log",
    "spruce_wood",
    "mangrove_planks",
    "mangrove_log",
    "mangrove_wood",
    "crimson_planks",
    "crimson_stem",
    "warped_planks",
    "warped_stem",
    "cherry_planks",
    "cherry_wood",
    "cherry_log",
    "bamboo_planks",
    "pale_oak_planks",
    "pale_oak_log",
    "pale_oak_wood",

    "stone",
    "cobblestone",
    "cobbled_deepslate",
    "chiseled_deepslate",
    "polished_deepslate",
    "deepslate",
    "deepslate_bricks",
    "deepslate_tiles",
    "diorite",
    "andesite",
    "granite",
    "dirt",
    "grass_block",
    "podzol",

    "crafting_table",
    "furnace",
    "chest",
    "ladder",

    "end_stone",
    "obsidian",
    "end_bricks",
    "purpur_block",
    "purpur_pillar",

    "white_wool",
    "orange_wool",
    "magenta_wool",
    "purple_wool",
    "light_blue_wool",
    "blue_wool",
    "yellow_wool",
    "lime_wool",
    "pink_wool",
    "gray_wool",
    "light_gray_wool",
    "black_wool",
    "brown_wool",
    "red_wool",
    "cyan_wool",

    "scaffolding",
    "brick_block",
    "mud_bricks",
    "mossy_stone_bricks",
    "prismarine_bricks",
    "stone_bricks",


    






];

// 能偷的物品类物品
const itemsCanSnatchItems = [
    // 食物
    "apple",
    "baked_potato",
    "beetroot",
    "beetroot_soup",
    "bread",
    "cake",
    "carrot",
    "chorus_fruit",
    "cooked_beef",
    "cooked_chicken",
    "cooked_cod",
    "cooked_mutton",
    "cooked_porkchop",
    "cooked_rabbit",
    "cooked_salmon",
    "cookie",
    "dried_kelp",
    "dried_kelp_block",
    "enchanted_golden_apple",
    "golden_apple",
    "golden_carrot",
    "honey_bottle",
    "melon_slice",
    "mushroom_stew",
    "poisonous_potato",
    "potato",
    "pufferfish",
    "pumpkin_pie",
    "rabbit_stew",
    "beef",
    "chicken",
    "cod",
    "mutton",
    "porkchop",
    "rabbit",
    "salmon",
    "rotten_flesh",
    "spider_eye",
    "cooked_beef",
    "suspicious_stew",
    "sweet_berries",
    "tropical_fish",
    "glow_berries",

    // 矿石
    "copper_ingot",
    "gold_ingot",
    "iron_ingot",
    "netherite_ingot",
    "amethyst_shard",
    "diamond",
    "emerald",
    "lapis_lazuli",
    "quartz",

];

// 能偷的方块类物品
const itemsCanSnatchBlocks = [

    //建筑方块
    "oak_planks",
    "oak_log",
    "oak_wood",
    "acacia_planks",
    "acacia_log",
    "acacia_wood",
    "birch_planks",
    "birch_log",
    "birch_wood",
    "dark_oak_planks",
    "dark_oak_log",
    "dark_oak_wood",
    "jungle_planks",
    "jungle_log",
    "jungle_wood",
    "spruce_planks",
    "spruce_log",
    "spruce_wood",
    "mangrove_planks",
    "mangrove_log",
    "mangrove_wood",
    "crimson_planks",
    "crimson_stem",
    "warped_planks",
    "warped_stem",
    "cherry_planks",
    "cherry_wood",
    "cherry_log",
    "bamboo_planks",
    "pale_oak_planks",
    "pale_oak_log",
    "pale_oak_wood",

    "stone",
    "cobblestone",
    "cobbled_deepslate",
    "chiseled_deepslate",
    "polished_deepslate",
    "deepslate",
    "deepslate_bricks",
    "deepslate_tiles",
    "diorite",
    "andesite",
    "granite",
    "dirt",
    "grass_block",
    "podzol",

    "crafting_table",
    "furnace",
    "chest",
    "ladder",

    "end_stone",
    "obsidian",
    "end_bricks",
    "purpur_block",
    "purpur_pillar",

    "white_wool",
    "orange_wool",
    "magenta_wool",
    "purple_wool",
    "light_blue_wool",
    "blue_wool",
    "yellow_wool",
    "lime_wool",
    "pink_wool",
    "gray_wool",
    "light_gray_wool",
    "black_wool",
    "brown_wool",
    "red_wool",
    "cyan_wool",

    "scaffolding",
    "brick_block",
    "mud_bricks",
    "mossy_stone_bricks",
    "prismarine_bricks",
    "stone_bricks",


    






];


const itemsThatPrecious = [
    "end_scroll",
    "mask_of_eyes",
    "stasis_potion",
];

// 全局定时器
system.runInterval(() => {
    dimensions.forEach(dim => {
        const dimensionObj = world.getDimension(dim);
            if (dimensionObj) {
                const entityArray = dimensionObj.getEntities({ type: 'pm_mock:the_snatching' });
                for (const entity of entityArray) {

                    // 定时检查生物是不是应该传送了
                    if (entity.getProperty('pm_mock:teleport_countdown') == 0) {
                        const randomCountdown = Math.floor(Math.random() * 21) + 10;
                        entity.setProperty('pm_mock:teleport_countdown', randomCountdown);

                        // 只有指定状态下才能传送
                        if (entity.getProperty('pm_mock:skill_state') == 0 || entity.getProperty('pm_mock:skill_state') == 1 || entity.getProperty('pm_mock:skill_state') == 3) {
                            entity.setProperty('pm_mock:teleport_state', -1 );
                        }
                        
                    }
                    else {
                        entity.setProperty('pm_mock:teleport_countdown', entity.getProperty('pm_mock:teleport_countdown') - 1);
                    }

                    // 定时处理游戏超时计时器
                    if ((entity.getProperty('pm_mock:wait_countdown') >= 1)&& (entity.getProperty('pm_mock:skill_state') === 4)) {
                        entity.setProperty('pm_mock:wait_countdown', entity.getProperty('pm_mock:wait_countdown') - 1 );
                        // console.warn(`${entity.name} 倒计时：${entity.getProperty('pm_mock:wait_countdown')}`);

                        // 显示字幕
                        let actionbar = "abc"
                        if (entity.getProperty('pm_mock:item_carryed_state') == 1) {
                            actionbar = "§eIs this the item you dropped?\n\n§r§aGrab it§r   §cSwitch item§r"
                        } else {
                            actionbar = "§eWhich one is the most precious item?\n\n§r§aGrab it§r   §cSwitch item§r"
                        }

                        entity.runCommand(`title @a[r=10] actionbar ${actionbar}`)
                    }
                    if ((entity.getProperty('pm_mock:wait_countdown') === 0)&& (entity.getProperty('pm_mock:skill_state') === 4)) {
                        entity.triggerEvent('skill_3');
                        entity.runCommand('title @a[r=16] actionbar §cTime up!');
                        entity.runCommand('playsound mock.the_snatching.finish @a ~~~');
                        // console.warn('游戏超时');
                    }



                    // 测试用
                    // 从上面的物品里随机选择一个触发
                    // const randomItemName = itemsCanSnatch[debugCurItemIndex];
                    // entity.triggerEvent(`snatch_${randomItemName}`);
                    // debugCurItemIndex = (debugCurItemIndex + 1) % itemsCanSnatch.length;
                    // console.warn(`测试物品：${randomItemName}`)

                }
                
            }
    });
}, 10);

// 传送技能函数
export function teleportSkill(entity) {
    try {
        let teleportLocation = null;
        let attempts = 0;
        const maxAttempts = 10; // 最大尝试次数

        while (attempts < maxAttempts && teleportLocation === null) {
            const randomX = Math.floor(Math.random() * 31) - 15;
            const randomZ = Math.floor(Math.random() * 31) - 15;

            for (let y = 5; y >= -5; y--) {
                const blockLocation = { x: entity.location.x + randomX, y: entity.location.y + y, z: entity.location.z + randomZ };
                const block = entity.dimension.getBlock(blockLocation);

                if (block) {
                    if (!block.isAir && !block.isLiquid && !block.isWaterlogged) {
                        // 传送到这个方块上方一格
                        teleportLocation = { x: blockLocation.x, y: blockLocation.y + 2, z: blockLocation.z };
                        break;
                    }
                }
            }

            attempts++;
        }

        if (teleportLocation) {
            entity.teleport(teleportLocation, { checkForBlocks: true });
        }
    } catch (error) {
        // console.error(`Error in teleportSkill for entity ${entity.name}:`, error);
    }
}

// 触发skill4事件，开始记忆游戏
function handleSkill4(sourceEntity) {
    const inventoryComponent = sourceEntity.getComponent('minecraft:inventory');
    if (inventoryComponent) {
        const container = inventoryComponent.container;

        // 背包1号和2号位从可抢夺物品中随机选一个set进去
        for (let i = 1; i <= 2; i++) {
            const randomItemName = itemsCanSnatch[Math.floor(Math.random() * itemsCanSnatch.length)];
            const randomItemStack = new ItemStack(randomItemName, 1);
            container.setItem(i, randomItemStack);
        }

        // 如果实体有pm_mock:item_carryed_state这个property且值为0，那把0号位也随机选一个set进去
        if (sourceEntity.getProperty('pm_mock:item_carryed_state') === 0) {
            const randomItemName = "pm_mock:" + itemsThatPrecious[Math.floor(Math.random() * itemsThatPrecious.length)];
            const randomItemStack = new ItemStack(randomItemName, 1);
            container.setItem(0, randomItemStack);
        }

        // 将pm_mock:cur_item_index这个property设为012中的随机值
        const randomIndex = Math.floor(Math.random() * 3);
        sourceEntity.setProperty('pm_mock:cur_item_index', randomIndex);

        // 将pm_mock:wait_countdown这个property设为
        sourceEntity.setProperty('pm_mock:wait_countdown', memoryGameWaitTime);

        // 音效
        sourceEntity.runCommand('playsound mock.the_snatching.start @a ~~~');

        // 根据当前物品索引值，取物品名，触发这个实体的对应事件
        const itemInSlot = container.getItem(randomIndex);
        if (itemInSlot) {
            const itemName = itemInSlot.typeId;


            // 触发这个实体的事件snatch_物品名
            const eventName = `snatch_${itemName.split(':')[1]}`;
            system.runTimeout(() => {
                sourceEntity.triggerEvent(eventName);
            }, 20 * 0.6);
        }
    }
}

//触发技能4切换物品
function handleSkill4Switch(sourceEntity) {
    const inventoryComponent = sourceEntity.getComponent('minecraft:inventory');
    if (inventoryComponent) {
        const container = inventoryComponent.container;

        // 读取pm_mock:cur_item_index这个property
        let curItemIndex = sourceEntity.getProperty('pm_mock:cur_item_index');

        // 循环0-2
        curItemIndex = (curItemIndex + 1) % 3;
        sourceEntity.setProperty('pm_mock:cur_item_index', curItemIndex);

        // 从实体对应物品栏位掏出新的物品
        const itemInSlot = container.getItem(curItemIndex);
        if (itemInSlot) {
            const itemName = itemInSlot.typeId;


            // 触发这个实体的事件snatch_物品名
            const eventName = `snatch_${itemName.split(':')[1]}`;
            system.runTimeout(() => {
                sourceEntity.triggerEvent(eventName);
            }, 20 * 1);
        }

        // 重置waittime
        sourceEntity.setProperty('pm_mock:wait_countdown', memoryGameWaitTime);
    }
}

// 技能4确认物品
function handleSkill4Confirm(sourceEntity) {
    const curItemIndex = sourceEntity.getProperty('pm_mock:cur_item_index');

    // 检查物品索引是否为0
    const isIndexZero = curItemIndex === 0;

    // warn一下结果
    // console.warn(`pm_mock:cur_item_index is 0: ${isIndexZero}`);

    // 选择正确
    if (isIndexZero) {
        sourceEntity.runCommand(`title @a[r=16] actionbar §aWise choice!`);
        sourceEntity.runCommand('playsound mock.the_snatching.finish @a ~~~');
        sourceEntity.runCommand('playsound random.levelup @a ~~~');

        // 获取实体物品栏0号位的物品
        const inventoryComponent = sourceEntity.getComponent('minecraft:inventory');
        if (inventoryComponent) {
            const container = inventoryComponent.container;
            const itemInSlot = container.getItem(0);

            if (itemInSlot) {
                const itemName = itemInSlot.typeId;

                // 使用loot指令掉落物品
                sourceEntity.runCommand(`loot spawn ~~~ loot "snatch_table/snatch_${itemName.split(':')[1]}"`);

                // 清空实体物品栏0号位
                container.setItem(0, null);
                sourceEntity.setProperty('pm_mock:item_carryed_state', 0);

                // 额外掉落奖励
                sourceEntity.runCommand(`loot spawn ~~~ loot "mobs/the_snatching_award"`);
            }
        }
    } else {
        sourceEntity.runCommand(`title @a[r=16] actionbar §cWrong choice!`);
        sourceEntity.runCommand('playsound mock.the_snatching.finish @a ~~~');
    }

    // 重置状态
    sourceEntity.triggerEvent("skill_3");
    sourceEntity.triggerEvent("snatch_empty");
}

// 偷玩家物品
function stealPlayerItem(entity) {
    // 获取实体周围10格内的玩家
    const players = entity.dimension.getPlayers({ location: entity.location, maxDistance: 10 });

    // 只处理第一个玩家
    if (players.length > 0) {
        entity.runCommand(`camerashake add @a[r=6] 0.3 0.3 rotational`);
        const player = players[0];
        const playerInventory = player.getComponent('minecraft:inventory').container;

        // 遍历玩家的物品栏
        for (let i = 0; i < playerInventory.size; i++) {
            const item = playerInventory.getItem(i);
            if (item) {
                const itemName = item.typeId;

                // 检查这个名称是否匹配可抢夺物品中的任意一个
                const isMatch = itemsCanSnatch.some(item => `minecraft:${item}` === itemName);

                if (isMatch) {
                    // 偷走这个物品
                    const itemStack = playerInventory.getItem(i);
                    if (itemStack.amount > 1) {
                        itemStack.amount--;
                        playerInventory.setItem(i, itemStack); // 更新玩家物品栏中的物品数量
                    } else {
                        playerInventory.setItem(i, null); // 移除玩家物品栏中的物品
                    }

                    const stolenItemStack = new ItemStack(itemName, 1);
                    const entityInventory = entity.getComponent('minecraft:inventory').container;
                    entityInventory.setItem(0, stolenItemStack); // 放到实体物品栏0号位

                    // 设置实体的pm_mock:item_carryed_state为1
                    entity.setProperty('pm_mock:item_carryed_state', 1);

                    // 触发对应事件，把物品放到自己手里
                    const eventName = `snatch_${itemName.split(':')[1]}`;
                    entity.triggerEvent(eventName);

                    // 给被偷物品的玩家发送字幕提示
                    // 检查这个名称是否匹配可抢夺物品中的任意一个
                    const isMatchItem = itemsCanSnatchItems.some(item => `minecraft:${item}` === itemName);
                    if (isMatchItem) {
                        player.onScreenDisplay.setActionBar([
                            { text: "Oh no! The Snatchling stole your §e" },
                            { translate: `item.${itemName.split(':')[1]}.name` },
                            { text: "§r!"},
                        ]);
                    }
                    else {
                        player.onScreenDisplay.setActionBar([
                            { text: "Oh no! The Snatchling stole your §e" },
                            { translate: `tile.${itemName.split(':')[1]}.name` },
                            { text: "§r!"},
                        ]);
                    }
                    

                    // 只对被偷物品的玩家使用镜头摇晃效果
                    player.runCommand(`camerashake add @s 0.3 0.3 rotational`);
                    player.runCommand(`playsound mock.the_snatching.be_stolen`);

                    // warn一下结果
                    // console.warn(`Stole item ${itemName} from player ${player.name}`);

                    return; // 偷到一个物品后结束函数
                }
            }
        }
    }

    // warn一下结果（如果没有找到匹配物品）
    // console.warn(`No matching items found to steal from nearby players`);
    // 没有偷到任何物品就播放一个粒子
    entity.dimension.spawnParticle('pm_mock:the_snatching_fail_1', entity.location);
}

// 检查周围有没有紫颂植物
function checkForChorusPlant(entity, radius = 8) {
    try {
        const entityLocation = entity.location;

        // 定义检测范围
        const startX = entityLocation.x - radius;
        const endX = entityLocation.x + radius;
        const startZ = entityLocation.z - radius;
        const endZ = entityLocation.z + radius;

        // 遍历检测范围内的所有方块
        for (let x = startX; x <= endX; x++) {
            for (let z = startZ; z <= endZ; z++) {
                for (let y = entityLocation.y - 1; y <= entityLocation.y + 1; y++) {
                    const blockLocation = { x: x, y: y, z: z };
                    const block = entity.dimension.getBlock(blockLocation);

                    if (block && block.typeId === 'minecraft:chorus_plant') {
                        // console.warn('Found chorus plant!');
                        return; // 找到紫颂植物后结束函数
                    }
                }
            }
        }

        // console.warn('No chorus plant found.');
    } catch (error) {
        // console.error(`Error in checkForChorusPlant for entity ${entity.name}:`, error);
    }
}


// // 监听生物生成
// world.afterEvents.entitySpawn.subscribe((event) => {
//     const { cause, entity } = event;
//     if (entity) {
//         console.warn(`Spawning entity ${entity.typeId}, cause: ${cause}`);
//     } 
//     else {
//         log(`The entity event did not work as expected.`, -1);
//     }
// });

