function xhr(url)
{
    return new Promise(function(resolve, reject) {
        var req = new XMLHttpRequest();
        req.open('GET', url);

        req.onload = function()
        {
            if (req.status != 200)
                reject(new Error(req.statusText));
            
            resolve(req.response);
        };

        req.onerror = function() {
            reject(new Error("There was a problem loading " + url));
        };

        req.send();
    });
}

function getJson(url)
{
    return xhr(url)
        .then(function(value) {
            try {
                return JSON.parse(value);
            } catch (e) {
                throw e;
            }
        });
}

function getStartOver()
{
    return getJson("//smp.ngtv.io/admin/audit?type=startover")
        .then(filterStartOver); // Filtering out copies/duplicates
}

function filterStartOver(result) 
{
    var showIds = [];

    return {
        messages: result.messages.filter(function(el) {
            var showId = el.lmdbInfo.show_id;
            if (showIds.indexOf(showId) == -1)
            {
                showIds.push(showId);
                return true;
            }
            return false;
        })
    };
}

var token = "?hdnea=exp=1529291028~acl=/hls/live/*~id=6f897c77e2da49d2866ba79866530b5c81428512~hmac=b97f6d79116b9dda405d055de9d63f0eb2a41e0562fbafe8fd2934a32c8dc66c ";

var json; // Set loaded startover json to a global var to help update index
var index = 0;

function setGlobalJson(result) {
    json = result;
    return result;
}

function updateUI(result)
{
    return new Promise(function(resolve, reject)
    {
        try {
            var current = result.messages[index];
            var urls    = current.message.packaging[0].urls;
            var url     = urls[0];
            
            document.querySelector(".series-name").innerHTML = current.lmdbInfo.series_name;
            document.querySelector(".summary").innerHTML     = current.lmdbInfo.summary;
            document.querySelector(".time").innerHTML        = new Date(current.message.inbandTimestamp);
        
            resolve(url);
        } catch (error) {
            reject(error);
        }
    });
}

function getStartOverAndPlay() {
    return getStartOver()
        .then(setGlobalJson)
        .then(updateUI)
        .then(playContent)
        .catch(console.warn);
}

function playCurrent() {
    index = 0; // Reset to the current index
    getStartOverAndPlay();
}

function playPrevious() {
    if (json && index < json.messages.length - 1)
    {
        index++;
        getStartOverAndPlay();
    }
}

function playNext() {
    if (index > 0)
    {
        index--;
        getStartOverAndPlay();
    }
}