// properties:
// -----------
// server - selected server name)
// serverUrl - Url of the selected server
// stations - Number of stations in selected server
// tags - Number of tags in selected server
// countries - Number of countries in selected server
// count - Number of servers in model
// model - Model containing list of servers (if you want to manually choose server)
// --------------------------------------------------------------------------------
// functions:
// ----------
// getList - Refresh the ListModel and add a random url to server
// getRandom - Get a random url from the ListModel and add url to server
// ---------------------------------------------------------------------
import QtQuick 2.0
import "../models"

Item {
    property string _useragent: "AllRadio/2.0.0 (test) (SailfishOS; Linux) nesnomis@gmail.com"
    property int _tags: 0
    property int _countries: 0
    property int _c: 0
    // Properties to be used in application -------------------------------------------------
    property ListModel serversModel : ListModel { id: serversModel }
    property ListModel votedModel : ListModel {id: votedModel}
    property CountryListModel countriesModel : CountryListModel {id:countriesModel}
    //property TagListModel tagsModel : TagListModel {id:tagsModel}
    property string serverUrl: ""
    property string server: ""
    property bool online: false
    property bool voted: false
    property int stationCount: 0
    property int tagCount: 0
    //property int viewTagCount: tagsModel.maxCount
    property int countryCount: 0
    property bool loading: stationCount !== 0 && tagCount !== 0 && countryCount !== 0 ? false : true
    property int serverIndex: 0
    property int connectIndex: -1
    property string lookup: sModel.get(serverIndex).url //"http://fi2.api.radio-browser.info/json/servers"
    // ---------------------------------------------------------------------------------------
    Timer {
        id: sTimer
        interval: 2000; running: false; repeat: false
        onTriggered: {
            if (serverIndex < sModel.count-1) serverIndex = serverIndex + 1; else serverIndex = 0
            getList()
        }
    }
    //onServerIndexChanged: console.log(" ******* LOOKUP ******** ")+serverIndex

    ListModel {
        id: sModel

        ListElement {
            name: "all.api.radio-browser.info"
            url: "http://all.api.radio-browser.info/json/servers"
        }
        ListElement {
            name: "de1.api.radio-browser.info"
            url: "http://de1.api.radio-browser.info/json/servers"
        }
        ListElement {
            name: "de2.api.radio-browser.info"
            url: "http://de2.api.radio-browser.info/json/servers"
        }
        ListElement {
            name: "fi1.api.radio-browser.info"
            url: "http://fi1.api.radio-browser.info/json/servers"
        }
        ListElement {
            name: "fi3.api.radio-browser.info"
            url: "http://fi3.api.radio-browser.info/json/servers"
        }
    }

    onOnlineChanged: {
        if (online && serverUrl !== "") {
            countriesModel.source = serverUrl  + "/xml/countrycodes?hidebroken=true"
        }
    }
    // Not used?!?!?
  /*  function getServer(s,u) {
        stationCount = 0
        tagCount = 0
        countryCount = 0
        server = s
        serverUrl = u
        getStats()
    } */

    // Choose a random server from available servers
    function getRandom(url) {
        if (serversModel.count > 0) {
            var random = Math.floor((Math.random() * serversModel.count) + 1) - 1
            serverUrl = serversModel.get(random).serverUrl
            server = serversModel.get(random).server
            if (serverUrl.length > 7 && url !== serverUrl) {sTimer.running=false;getStats();} else getRandom();
        }
    }

    // Get a list of available Radio Community Servers.
    function getList() {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function () {
            if (req.readyState === 4 && req.status < 300) {

                var obj = JSON.parse(req.responseText)
                serversModel.clear()
                for (var key in obj) {
                    addIfNotExist(obj[key])
                }
                sTimer.running = false
                //console.log(" *** lookup *** "+serverIndex+": "+lookup)
                getRandom(lookup)
            } else if (req.readyState === 4 && req.status > 299) {
                if (serverIndex < sModel.count-1) serverIndex=serverIndex+1; else serverIndex=0;
                lookup=sModel.get(serverIndex).url
                //console.log(" *** lookup *** "+serverIndex+": "+lookup)
                getList();
            }
        };
        sTimer.running = true
        //console.log(" *** START : "+lookup)
        req.open("get", lookup);
        req.setRequestHeader('User-Agent',_useragent);
        req.send();
    }
    // Add available server to listmodel
    function addIfNotExist(server) {
        for (var i = 0; i < serversModel.count; i++) {
            if (serversModel.get(i).server === server.name) {
                return
            }
        }
        serversModel.append({"serverUrl": "http://"+server.name,"server": server.name})
    }
    // ----------------------------------------------
    // Station online?
    function getStats() {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function () {
            if (req.readyState === 4 && req.status < 300) {
                var obj = req.response.split("{").pop();
                obj = JSON.parse("{"+obj)
                if (obj.status === "OK") {
                    stationCount = obj.stations-obj.stations_broken
                    tagCount = obj.tags
                    if (obj.status === "OK") {online = true} else {online = false}
                }
            }
        };
        req.open("get", serverUrl+"/json/stats");
        req.setRequestHeader('User-Agent',_useragent);
        req.send();
    }
    // ----------------------------------------------
    // Vote/like for radio station on community radio browser.
    function upVote(stationuuid,returnValue) {
        var req = new XMLHttpRequest();
        var ret = false
        req.onreadystatechange = function () {
            if (req.readyState === 4 && req.status === 200) {
                var obj = req.response.split("{").pop();
                obj = JSON.parse("{"+obj)
                if (obj.ok) {
                    if (obj.ok) {returnValue=true;console.log(" ****** VOTED *****")} else {returnValue=false;console.log(" ****** NOT VOTED *****")}
                }
                return ret
            }
        };
        req.open("get", serverUrl+"/json/vote/"+stationuuid);
        req.setRequestHeader('User-Agent',_useragent);
        req.send();
    }
    // ----------------------------------------------
    // Load model with country names.
    CountryNameModel {id: countryNameModel}

    function getCountryName(land) {  // Get translated countryname
        for(var i = 0; i < countryNameModel.count; i++) {
            var current = countryNameModel.get(i);
            if(land === current.code) {
                return countryNameModel.countryname(i)
            }
        }
    }
}
