/// <reference path="../Elements.ts" />
module Elements.BGMHandler {
    var player = <HTMLAudioElement> document.getElementById("bgmPlayer");
    player.volume = 0.1;
    player.addEventListener("canplay", function () {
        this.play();
        this.style.display = "";
    });
    player.addEventListener("error", function () {
        this.style.display = "none";
        console.warn("Could not play the BGM ", this.src);
    });
    player.addEventListener("pause", function () {
        this.style.display = "none";
    });

    function getJsonFromUrl(url) : any {
        if(!url) url = location.search;
        var query = url.substr(1);
        var result = {};
        query.split("&").forEach(function(part) {
            var item = part.split("=");
            result[item[0]] = decodeURIComponent(item[1]);
        });
        return result;
    }

    export function playYT (vidID : string) {
        let proxyURL = "https://images" + (Math.floor(Math.random() * 33)) + "-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=";
        let vidInfo = encodeURIComponent("https://www.youtube.com/get_video_info?video_id=") + encodeURIComponent(vidID);
        fetch(proxyURL + vidInfo).then(response => {
            if (response.ok) {
                response.text().then((data : any) => {
                    data = getJsonFromUrl(data);
                    let streams = (data.url_encoded_fmt_stream_map + ',' + data.adaptive_fmts).split(',');

                    let valid = [];

                    for (let i = 0; i < streams.length; i++) {
                        let stream = getJsonFromUrl(streams[i]);
                        if (stream.type && stream.type.indexOf("audio") == 0) {
                            valid.push(stream.url);
                        }
                    }

                    // Last one has highest quality, if none found results "undefined" which just doesn't play
                    player.src = valid.pop();
                });
            }
        });
    }

    /** TODO: Allow players to create a playlist of youtube URLs that vary with certain situations, then play one of those randomly every time situation arises
              e.g.: A list of songs for Combat, Exploration in the Forest, Talking with the Witch, etc.

     */
}