import Vector3 from "../core/geom/Vector3.js";
import { SerializationMetadata } from "./ecs/components/SerializationMetadata.js";
import Timer from './ecs/components/Timer.js';
import Entity from './ecs/Entity.js';
import { Transform } from './ecs/transform/Transform.js';
import { SequenceBehavior } from "./intelligence/behavior/composite/SequenceBehavior.js";
import { BehaviorComponent } from "./intelligence/behavior/ecs/BehaviorComponent.js";
import { DieBehavior } from "./intelligence/behavior/ecs/DieBehavior.js";
import { DelayBehavior } from "./intelligence/behavior/util/DelayBehavior.js";
import { SoundEmitter } from './sound/ecs/emitter/SoundEmitter.js';
import { SoundEmitterChannels } from "./sound/ecs/emitter/SoundEmitterSystem.js";

/**
 *
 * @param {Vector3} [position]
 * @param {number} [timeout]
 * @param {String} [url]
 * @param {SoundTrack} [track]
 * @param {boolean} [positioned]
 * @param {String|SoundEmitterChannels} [channel]
 * @param {number} [volume]
 * @returns {Entity}
 */
export function createSound(
    {
        position = Vector3.zero,
        timeout = 60,
        url,

        track,
        positioned = true,
        channel = SoundEmitterChannels.Effects,
        volume = 1
    }
) {

    const builder = new Entity();

    let trackJSON;

    if (url !== undefined) {
        trackJSON = {
            url: url,
            startWhenReady: true
        };
    } else {
        trackJSON = track.toJSON();
    }

    const soundEmitter = SoundEmitter.fromJSON({
        tracks: [trackJSON],
        isPositioned: positioned,
        volume: volume,
        loop: false,
        channel
    });


    const soundTrack = soundEmitter.tracks.last();
    soundTrack.on.ended.add(builder.destroy, builder);

    builder
        .add(SerializationMetadata.Transient) //make sound transient
        .add(BehaviorComponent.from(SequenceBehavior.from([
            DelayBehavior.from(timeout),
            DieBehavior.create()
        ])))
        .add(Transform.fromJSON({ position: position }))
        .add(soundEmitter);
    return builder;
}

/**
 *
 * @param timeout
 * @param action
 * @returns {Entity}
 */
export function createTimer({ timeout, action }) {
    const builder = new Entity();

    function suicide() {
        builder.destroy();
    }

    builder.add(new Timer({
        timeout,
        actions: [
            action,
            suicide
        ]
    }));

    return builder;
}