import * as mc from '@minecraft/server';
import * as lib from '../lib/lib';
import * as config from '../pb_scraft_config';

import { deleteProjectile, registerProjectile } from '../lib/projectile_tracker';
import { SPELL_PLAYERS } from '../pb_scraft_player';


export default class SpellProjectile {

    player;
    cooldown;
    name;
    manacost;
    castTime;
    soundCast;
    projectileData;

    timeIndex = 0;
    isCharged = true;
    isActive = true;

    totalTime;

    constructor(player, spellData) {
        this.player = player;

        this.name = spellData.identifier;
        this.manacost = spellData.manacost;;
        this.castTime = spellData.castTime;;
        this.cooldown = spellData.cooldown;
        this.soundCast = spellData.soundCast;
        this.projectileData = config.PROJECTILE_LIST.find((f) => f.identifier == spellData.projectile);

        this.totalTime = this.castTime + this.cooldown;
    }

    cast() {
        this.player.playSound(this.soundCast, this.player.location);
    }

    stop() {
        this.isActive = false;
        lib.setCooldown(this.player, 0);
    }

    release() {

    }

    trigger() {
        lib.setCooldown(this.player, this.cooldown);
        const dimension = this.player.dimension;
        const view_vector = this.player.getViewDirection();
        const location = this.player.getHeadLocation();
        const impulse = this.projectileData.impulse;

        SPELL_PLAYERS.get(this.player.id).consumeMana(this.manacost);

        const projectile = mc.world.getDimension(dimension.id).spawnEntity(this.projectileData.identifier, { x: location.x + view_vector.x * 2, y: location.y + 0.75, z: location.z + view_vector.z * 2 });
        registerProjectile(projectile, this.projectileData);

        const component = projectile.getComponent("minecraft:projectile");
        component.owner = this.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(this.projectileData.soundLaunch, location);
    }

    tick() {
        if (this.isActive) {
            if (this.timeIndex <= this.castTime) {
                if (this.timeIndex % 20 == 0) this.cast();
                lib.setCooldown(this.player, 110);
            }
            if (this.timeIndex == this.castTime) this.trigger();
            if (this.timeIndex >= this.totalTime) this.isActive = false;
            this.timeIndex++;
        }
    }
}