import * as mc from '@minecraft/server';

import { beamBetweenLocations } from "./beam_utils";

export const PROJECTILES = new Map();
const TICK_INTERVAL = 1;

mc.system.runInterval(() => {
    for (let projectile of PROJECTILES.values()) {
        if (projectile.entity.isValid()) projectile.tick();
        else deleteProjectile(projectile.entity);
    }
}, TICK_INTERVAL);

export function registerProjectile(projectile, data) {
    PROJECTILES.set(projectile, new Projectile(projectile, data));
}

export function deleteProjectile(projectile) {
    PROJECTILES.delete(projectile);
}

export class Projectile {

    entity;
    dimension;
    location;
    previous_location;
    particle_track;

    hasTrackingParticle = false;
    hasTickingParticle = false;

    constructor(projectile, data) {
        this.entity = projectile;
        this.particle_track = data.particle_track;
        this.particle_tick = data.particle_tick;
        this.dimension = projectile.dimension;
        this.location = this.entity.location;
        this.previous_location = this.location;

        if (data.particle_track != undefined) this.hasTrackingParticle = true;
        if (data.particle_tick != undefined) this.hasTickingParticle = true;
    }

    tick() {
        if (!this.entity.isValid()) {
            deleteProjectile(this.entity);
            return;
        }

        this.previous_location = this.location;
        this.location = this.entity.location;

        if (this.hasTickingParticle) this.particle_tick.forEach(element => { mc.world.getDimension(this.dimension.id).spawnParticle(element, this.location); });
        if (this.hasTrackingParticle) beamBetweenLocations(this.previous_location, this.location, this.dimension.id, this.particle_track);
    }
}