import * as mc from "@minecraft/server"
import * as config from '../pb_scraft_config.js';
import * as item_assembler from "./item_assembler.js";

handleEvents();

function handleEvents() {
    mc.system.afterEvents.scriptEventReceive.subscribe((eventData) => {
        const { id, sourceEntity, message, sourceBlock } = eventData;

        if (id == "pb_scraft:projectile") launchProjectileBlock(message, sourceBlock.location, sourceBlock.dimension);
        if (id == "pb_scraft:test_craft_spell") testCraftSpell(message, sourceEntity);
    })

}


export function launchProjectile(identifier, player) {

    let dimension = player.dimension;
    let view_vector = player.getViewDirection();
    let location = player.getHeadLocation();

    const data = config.EFFECT_LIST.find((f) => f.identifier == identifier);
    if (data == undefined) return;

    const impulse = data.impulse;

    const projectile = mc.world.getDimension(dimension.id).spawnEntity(identifier, { x: location.x, y: location.y + 1, z: location.z });
    if(data.particle_track != undefined) registerProjectile(projectile, data);
    
    const component = projectile.getComponent("minecraft:projectile");
    component.owner = player;

    projectile.addEffect('slow_falling', 2*mc.TicksPerSecond, { amplifier: 1, showParticles: false });
    component.shoot({ x: view_vector.x * impulse, y: view_vector.y * impulse, z: view_vector.z * impulse });
    dimension.playSound(data.soundLaunch, location);
}

function launchProjectileBlock(identifier, location, dimension) {

    const data = config.EFFECT_LIST.find((f) => f.identifier == identifier);
    if (data == undefined) return;

    const view_vector = { x: 1, y: 0, z: 0 };
    const impulse = data.impulse;

    const projectile = mc.world.getDimension(dimension.id).spawnEntity(identifier, { x: location.x, y: location.y + 1, z: location.z });
    dimension.playSound(data.soundLaunch, location);

    projectile.addEffect('slow_falling', 1000, { amplifier: 1, showParticles: false });
    projectile.clearVelocity();
    projectile.applyImpulse({ x: view_vector.x * impulse, y: view_vector.y * impulse, z: view_vector.z * impulse })
}

function testCraftSpell(message, player) {
    if (player == undefined) return;
    const spelldata = config.SPELL_LIST.find((f) => f.identifier == message);
    if (spelldata == undefined) return;

    const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
    const heldItem = mainhand.getItem();

    const itemdata = config.CAST_ITEM_LIST.find((f) => f.identifier == heldItem.typeId);
    if (itemdata == undefined) return;

    mainhand.setItem(item_assembler.applySpell(heldItem, itemdata, spelldata))
}