import { world, system } from "@minecraft/server";
import { handleItemDurability } from "./cavernite_pickaxe";

// 不可推动方块的 typeId 列表
const UnpushableBlockTypes = [
    "minecraft:barrier",
    "minecraft:beacon",
    "minecraft:bedrock",
    "minecraft:command_block",
    "minecraft:conduit",
    "minecraft:creaking_heart",
    "minecraft:crying_obsidian",
    "minecraft:enchanting_table",
    "minecraft:end_gateway",
    "minecraft:end_portal",
    "minecraft:end_portal_frame",
    "minecraft:ender_chest",
    "minecraft:grindstone",
    "minecraft:puzzle",
    "minecraft:jukebox",
    "minecraft:lodestone",
    "minecraft:spawner",
    "minecraft:piston",
    "minecraft:nether_portal",
    "minecraft:obsidian",
    "minecraft:reinforced_deepslate",
    "minecraft:respawn_anchor",
    "minecraft:sculk_catalyst",
    "minecraft:sculk_sensor",
    "minecraft:sculk_shrieker",
    "minecraft:structure_block",
    "minecraft:structure_void"
];

// 示例：如何检查一个方块是否是可推动方块
function isPushableBlock(block) {
    return !UnpushableBlockTypes.includes(block.typeId);
}

const useHammer = {
    onUse(event) {
        try {
            const player = event.source;

            player.playAnimation('animation.pm_mock_earthshaker_hammer.smash_tpp');
            // player.dimension.playSound('mock.earthshaker_hammer.hammer', player.location);

            system.runTimeout(() => {
                if (player.isValid()) {
                    player.dimension.playSound('mock.earthshaker_hammer.hammer', player.location);
                }
            }, 20 * 0.5);

            // 延迟施加伤害和击退
            system.runTimeout(() => {
                if (player.isValid()) {

                    const playerEquipmentComponent = player.getComponent('minecraft:equippable');
                    if (!playerEquipmentComponent) return;
                    const playerMainhandEquipment = playerEquipmentComponent.getEquipment('Mainhand');
                    if (!playerMainhandEquipment) return;
                    if (playerMainhandEquipment.typeId !== 'pm_mock:earthshaker_hammer') return;

                    player.addTag('pm_mock:earthshaker_hammer_user');

                    const playerLocation = player.location;
                    const forwardVector = player.getViewDirection();
                    const targetPos = {
                        x: playerLocation.x + forwardVector.x * 1.5,
                        y: playerLocation.y + 0.2,
                        z: playerLocation.z + forwardVector.z * 1.5
                    };

                    const dimension = player.dimension;
                    dimension.spawnParticle('pm_mock:earthshaker_hammer_1', targetPos);
                    const targetList1 = dimension.getEntities({
                        excludeTags: ['pm_mock:earthshaker_hammer_user'],
                        excludeTypes: ['minecraft:item', 'minecraft:xp_orb'],
                        location: targetPos,
                        maxDistance: 6,
                        minDistance: 0,
                    });
                    // const targetList2 = dimension.getEntities({
                    //     excludeTags: ['pm_mock:earthshaker_hammer_user'],
                    //     excludeTypes: ['minecraft:item', 'minecraft:xp_orb'],
                    //     location: targetPos,
                    //     maxDistance: 8,
                    //     minDistance: 5,
                    // });

                    targetList1.forEach(entity => {
                    
                        // 计算位置和方向并施加击退
                        const entityPos = entity.location;
                        const direction = { x: playerLocation.x - entityPos.x, y: playerLocation.y - entityPos.y, z: playerLocation.z - entityPos.z };
                        entity.applyKnockback(-direction.x, -direction.z, 2, 0.5);

                        entity.applyDamage(8, { cause: 'entityAttack', damagingEntity: player });
                        entity.addEffect('slowness', 60);
                    });

                    // targetList2.forEach(entity => {
                    
                    //     // 计算位置和方向并施加击退
                    //     const entityPos = entity.location;
                    //     const direction = { x: playerLocation.x - entityPos.x, y: playerLocation.y - entityPos.y, z: playerLocation.z - entityPos.z };
                    //     entity.applyKnockback(-direction.x, -direction.z, 2, 0.5);

                    //     entity.applyDamage(8, { cause: 'entityAttack', damagingEntity: player });
                    //     entity.addEffect('slowness', 60);
                    // });

                    player.removeTag('pm_mock:earthshaker_hammer_user');
                    handleItemDurability(player);
                }
            }, 20 * 1.75);
        } catch (error) {
            // console.error(`Error in earthshaker_hammer.js: ${error.message}`);
            // console.error(error.stack);
        }
    }
};

world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
    itemComponentRegistry.registerCustomComponent("pm_mock:earthshaker_hammer", useHammer);
});

// 左键点击方块？
world.afterEvents.entityHitBlock.subscribe(event => {
    const { hitBlock, damagingEntity, blockFace, hitBlockPermutation } = event;

    // 只回应 玩家使用锤子
    if (!damagingEntity)  return;
    if (damagingEntity.typeId !== 'minecraft:player') return;
    const playerEquipmentComponent = damagingEntity.getComponent('minecraft:equippable');
    const playerMainhandEquipment = playerEquipmentComponent.getEquipment('Mainhand');
    if (!playerMainhandEquipment) return;
    if (playerMainhandEquipment.typeId !== 'pm_mock:earthshaker_hammer') return;

    if  (!isPushableBlock(hitBlock)) {
        hitBlock.dimension.playSound('block.lantern.hit', hitBlock.location);
        return;
    }
    // 获取单位向量
    const direction = damagingEntity.getViewDirection();
    const primaryDirection = getPrimaryDirection(direction);

    const player = damagingEntity;
    const dimension = player.dimension;

    // 偏移位置
    const offsetLocation = {
        x: hitBlock.location.x + primaryDirection.x,
        y: hitBlock.location.y + primaryDirection.y,
        z: hitBlock.location.z + primaryDirection.z
    };

    const offsetBlock = dimension.getBlock(offsetLocation);

    if (offsetBlock && offsetBlock.isAir) {

        // 其他的不好使，就用clone吧
        dimension.runCommand(`clone ${hitBlock.location.x} ${hitBlock.location.y} ${hitBlock.location.z} ${hitBlock.location.x} ${hitBlock.location.y} ${hitBlock.location.z} ${offsetLocation.x} ${offsetLocation.y} ${offsetLocation.z} replace move`);
        dimension.playSound('close.iron_trapdoor', hitBlock.location);
        dimension.spawnParticle('pm_mock:earthshaker_hammer_2', hitBlock.bottomCenter());

        // system.runTimeout(() => {
        //     dimension.runCommand(`setblock ${hitBlock.location.x} ${hitBlock.location.y} ${hitBlock.location.z} air`);
        // }, 10);
        
        // dimension.runCommandAsync(`setblock ${hitBlock.location.x} ${hitBlock.location.y} ${hitBlock.location.z} air`);
        // dimension.setBlockType(hitBlock.location, "minecraft:air");
    } else {
        dimension.playSound('block.lantern.hit', hitBlock.location);
    }
});


// 获取主方向
function getPrimaryDirection(viewVector) {
    const { x, y, z } = viewVector;

    // 找出最大绝对值的分量
    const maxComponent = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));

    if (Math.abs(x) === maxComponent) {
        return { x: Math.sign(x), y: 0, z: 0 };
    } else if (Math.abs(y) === maxComponent) {
        return { x: 0, y: Math.sign(y), z: 0 };
    } else {
        return { x: 0, y: 0, z: Math.sign(z) };
    }
}