import { world, system } from "@minecraft/server";
import * as utils from "../utils";
import * as Vector3 from "../vector3";

const COOLDOWN_CATEGORY = "frostblizzard_scepter";
const COOLDOWN_DURATION = 30; // 30 ticks (1.5s)

const MAX_RANGE = 55;

const PROJECTILE_SPEED = 3;

export async function onItemUse(event) {
    const player = event.source;
    const cooldown = player.getItemCooldown(COOLDOWN_CATEGORY);
    if (cooldown > 0) return;

    // Disable player movement and camera
    // player.inputPermissions.movementEnabled = false;
    // player.inputPermissions.cameraEnabled = false;

    // Play third person animation
    utils.runPlayerCommand(player, `playanimation @s animation.goe_bos.player.throw_sword animation.goe_bos.player.fp_attack_v2 0 "v.is_first_person"`);
    utils.runPlayerCommand(player, `playanimation @s animation.goe_bos.player.fp_attack_v2 animation.goe_bos.player.throw_sword 0 "!v.is_first_person"`);
    utils.runPlayerCommand(player, `playanimation @s animation.goe_bos.player.throw_sword animation.player.empty 0 "q.all_animations_finished"`);
    utils.runPlayerCommand(player, `playanimation @s animation.goe_bos.player.fp_attack_v2 animation.player.empty 0 "q.all_animations_finished"`);

    // Delay projectiles
    system.runTimeout(() => {
        shoot(player);
        player.playSound("goe_bos:woosh");
        // player.dimension.spawnParticle("goe_bos:large_magic_circle_blue", player.location);
    }, 5);

    // Enable camera and movement
    // system.runTimeout(() => {
    //     player.inputPermissions.movementEnabled = true;
    //     player.inputPermissions.cameraEnabled = true;
    // }, 40);

    // Start cooldown
    player.startItemCooldown(COOLDOWN_CATEGORY, COOLDOWN_DURATION);

    damageHeldItem(player);
}

async function shoot(player) {
    const sourcePoint = new Vector3.Vector3(player.location);
    const spawnOffset = Vector3.rotateYAxis(player.getViewDirection(), 30);

    sourcePoint.x += spawnOffset.x;
    sourcePoint.y += 1.5;
    sourcePoint.z += spawnOffset.z;

    let targetPoint = new Vector3.Vector3(sourcePoint).add(new Vector3.Vector3(player.getViewDirection()).multiply(MAX_RANGE));
    const targetBlockHit = player.getBlockFromViewDirection({ maxDistance: MAX_RANGE });
    if (targetBlockHit) targetPoint = new Vector3.Vector3(targetBlockHit.block.location).add(targetBlockHit.faceLocation);

    const direction = Vector3.unit(Vector3.getVector(sourcePoint, targetPoint));

    const projectile = player.dimension.spawnEntity("goe_bos:frost_projectile", sourcePoint);
    let projectileComponent = projectile.getComponent("minecraft:projectile");
    projectileComponent.owner = player;
    projectileComponent.shoot({ 
        x: direction.x * PROJECTILE_SPEED, 
        y: direction.y * PROJECTILE_SPEED, 
        z: direction.z * PROJECTILE_SPEED 
    });
}

function damageHeldItem(player, amount = 1) {
    if (player.getGameMode() === "creative") return;
    
    const inventory = player.getComponent("minecraft:inventory").container;
    const selectedSlot = inventory.getSlot(player.selectedSlotIndex);
    const heldItem = selectedSlot.getItem();
    if (heldItem === undefined) return;

    const durabilityComponent = heldItem.getComponent("minecraft:durability");
    if (durabilityComponent === undefined) return;

    const itemDurability = durabilityComponent.maxDurability;
    const itemDamage = ++durabilityComponent.damage;

    if (itemDamage + 1 === itemDurability) {
        selectedSlot.setItem(undefined);
        return;
    }

    selectedSlot.setItem(heldItem);
}

export async function onEntityHurt(event) {
    const damageDealer = event.damageSource.damagingEntity;
    const shooter = damageDealer.getComponent("minecraft:projectile").owner;
    if (!shooter || shooter.typeId !== "minecraft:player")
        return;

    const hurtEntity = event.hurtEntity;
    try {
        if (hurtEntity.typeId === "minecraft:player") {
            hurtEntity.inputPermissions.movementEnabled = false;
            system.runTimeout(() => { hurtEntity.inputPermissions.movementEnabled = true } , 20);
        } else {
            hurtEntity.addEffect("slowness", 40, { amplifier: 255, showParticles: false });
        }

        hurtEntity.dimension.spawnParticle("goe_bos:snow_falling", hurtEntity.location);
    } catch (error) {}
}