class Playlist {

    constructor(audioRenderer, length) {

        this.audioRenderer = audioRenderer;

        this.currentTime = 0;
        this.icons = [];

        this.length = length;
    }

    addIcon(icon) {
        this.icons.push(icon);
        console.log(this.icons);
    }

    removeIcon(icon) {
        const index = this.icons.indexOf(icon);
        this.icons.splice(index, 1);
        console.log("removed", icon);
    }

    setCurrentTime(time) {
        this.currentTime = time;
    }

    stop() {
        this.icons.forEach((icon) => {
            icon.sound.stop();
        });
    }

    record() {
        const offlineRenderer = new Mobilizing.audio.OfflineRenderer({"length" : this.length});
        //console.log(offlineRenderer);
        //duplicate here all sounds to connect it to the rendrerer
        offlineRenderer.duplicateSourcesFromRenderer(this.audioRenderer);

        //tranfer the offsetStartTime for offlineRenderer
        for (let i = 0; i < offlineRenderer.sources.length; i++) {
            const source = offlineRenderer.sources[i];
            source.setOffsetStartTime(source.baseScheduleStartTime);
            console.log("clone source :", source);
            source.offlinePlay();
        };

        //render the offlineRenderer to a file
        offlineRenderer.startRendering();
        offlineRenderer.events.on("complete", (buffer) => {
            console.log("complete!", buffer);
            Mobilizing.audio.BufferToWav.downloadToWavFile(buffer, "sound");
        });
    }

    update() {

        this.icons.forEach((icon) => {

            //console.log(this.currentTime, icon.sound.baseScheduleStartTime, icon.sound.baseScheduleStartTime + icon.sound.duration );

            if (this.currentTime >= icon.sound.baseScheduleStartTime && this.currentTime < icon.sound.baseScheduleStartTime + icon.sound.duration) {

                icon.sound.setOffsetStartTime(this.currentTime - icon.sound.baseScheduleStartTime);

                //console.log("icon.sound.offsetStartTime", icon.sound.offsetStartTime);

                if (!icon.sound.playing) {
                    icon.sound.play();
                }
            }

        });
    }

}