// audio.js module
// Provides audio utilities
//
// Exports:
//   play
//      argument: playState (defaults to true)
//      plays or pauses audio depending on argument
//   pause
//      pauses audio (shorthand for play(false)
//   setAudioFile
//      argument: filePath
//      sets file to be played
//   playAudioFile
//      argument: filePath
//      sets file to be played and also initiates playing
//      shorthand for: setAudioFile(filePath); play();

import $ from "./jquery.module.js";

let $audio7gen;
let $audio7GenBkg;
let loopListener = null;

$(() => {
    $audio7gen = $("#audio7gen");
    if ($audio7gen.length === 0) {
        // Create element if it doesn't exist
        $audio7gen = $(`<audio id="audio7gen"></audio>`);
        $("body").append($audio7gen);
    }
});

async function play(playState = true, loop = false) {
    try {
        if (playState === true) {
            setLoop($audio7gen, loop);
            await $audio7gen[0].play();
        } else {
            $audio7gen[0].pause();
        }
    }
    catch(err) {
        console.log("In play in audio.js, caught error: ", err);
    }
}
async function playBackground(playState = true, loop = false) {
    try {
        if (playState === true) {
            setLoop($audio7GenBkg, loop);
            await $audio7GenBkg[0].play();
        } else {
            $audio7GenBkg[0].pause();
        }
    }
    catch(err) {
        console.log("In playBackground in audio.js, caught error: ", err);
    }

}

async function loopOnEnded(event) {
    try {
        this.currentTime = 0;
        await this.play();
    }
    catch(err) {
        console.log("In loopOnEnded in audio.js, caught error: ", err);
    }
}

function setLoop($element, loop) {
    if (!loopListener) {
        if (loop) {
            loopListener = loopOnEnded;
            $element.on("ended", loopListener);
        }
        else {
            $element.off(loopListener);
            loopListener = null;
        }
    }
}

function pause() {
    $audio7gen[0].pause();
}

/* SETS FILE PATH FOR AUDIO */
/* COMBINE WITH PLAY FUNCTION ABOVE TO PLAY AUDIO FILE */
function setAudioFile(filePath) {
    $audio7gen[0].pause();
    $audio7gen.attr("src", filePath);
}

function setAudioFileBkg(filePath) {
    $audio7GenBkg = $("#audio7genBkg");
    if ($audio7GenBkg.length === 0) {
        // Create element if it doesn't exist
        $audio7GenBkg = $(`<audio id="audio7genBkg"></audio>`);
        $("body").append($audio7GenBkg);
    }
    $audio7GenBkg[0].pause();
    $audio7GenBkg.attr("src", filePath);
}

/* SETS PATH AND PLAYS AUDIO FILE */
function playAudioFile(filePath, loop = false) {
    setAudioFile(filePath);
    play(true, loop)
}

function playAudioFileBackground(filePath, volume= null) {
    setAudioFileBkg(filePath);
    playBackground(true, true);
    if (volume) {
        $audio7GenBkg[0].volume = volume;
    }
}

export {play, pause, setAudioFile, playAudioFile, playAudioFileBackground};
