import Vector3 from "../../core/geom/Vector3.js";
import Timer from "../ecs/components/Timer.js";
import { Transform } from "../ecs/transform/Transform.js";
import { removeComponentsExcept } from "../ecs/util/removeComponentsExcept.js";
import Mesh from "../graphics/ecs/mesh/Mesh.js";
import { ParticleEmitter } from "../graphics/particles/particular/engine/emitter/ParticleEmitter.js";
import { SoundEmitter } from "../sound/ecs/emitter/SoundEmitter.js";
import { shutdownParticleEmitter, stopTrailAndNotifyOnceFinished } from "./AnimationUtils.js";
import EntityAnimation from "./EntityAnimation.js";
import TransitionFunctions from "./TransitionFunctions.js";


/**
 *
 * @param {number}  entity
 * @param {EntityComponentDataset} ecd
 * @returns {Promise}
 */
export function removeEntityStylish(entity, ecd) {
    //leave only model and transform
    removeComponentsExcept(ecd, entity, [Transform, Mesh, ParticleEmitter]);

    const duration = 2;

    //create animation
    const animation = new EntityAnimation(entity);

    const result = Promise.all([
        animation.promiseEnd(),
        stopEntityAndNotifyWhenStopped(entity, ecd)
    ]).then(function () {
        ecd.removeEntity(entity);
    });


    animation
        .translate(new Vector3(0, 2, 0), duration, TransitionFunctions.EaseIn)
        .fade(0, duration)
        .start(ecd);


    return result;
}

/**
 *
 * @param {number} entity
 * @param {EntityComponentDataset} ecd
 */
export async function stopSoundEmitterAndNotifyOnceFinished(entity, ecd) {

    if (!ecd.entityExists(entity)) {
        return;
    }

    const soundEmitter = ecd.getComponent(entity, SoundEmitter);


    if (soundEmitter === undefined) {
        return;
    }

    soundEmitter.fadeOutAllTracks(0.3);

    await Timer.createTimeoutPromise(ecd, 0.3);
}


/**
 *
 * @param {number} entity
 * @param {EntityComponentDataset} ecd
 * @returns {Promise}
 */
export function stopEntityAndNotifyWhenStopped(entity, ecd) {
    return Promise.all([
        shutdownParticleEmitter(entity, ecd),
        stopTrailAndNotifyOnceFinished(entity, ecd),
        stopSoundEmitterAndNotifyOnceFinished(entity, ecd)
    ]);
}
