// 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
    // 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 string lookup: "http://all.api.radio-browser.info/json/servers" //"http://all.api.radio-browser.info/json/servers"

    // ---------------------------------------------------------------------------------------

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

    function getRandom() {
        //console.log("getRandom")
        if (serversModel.count > 0) {
            var random = Math.floor((Math.random() * serversModel.count) + 1) - 1
            serverUrl = serversModel.get(random).serverUrl
            server = serversModel.get(random).server
            //console.log("getRandom: "+server)
            getStats()

        } //else getList()
    }

    function getList() {
        //console.log("getList")
        var req = new XMLHttpRequest();
        req.open("get", lookup,true);
        req.setRequestHeader('User-Agent',_useragent);
        req.timeout = 4000; // Set timeout to 4 seconds (4000 milliseconds)
        req.ontimeout = function () { console.log("Timed out!!!"); }
        //console.log("server 2")
        req.onreadystatechange = function () {
            //console.log(console.log("getList: "+req.status))
            if (req.readyState === 4 && req.status === 200) {
                var obj = JSON.parse(req.responseText)
                serversModel.clear()
                for (var key in obj) {
                    addIfNotExist(obj[key])
                }
                getRandom()
            } else if (req.readyState === 4 && req.status === 502) {lookup="http://de2.api.radio-browser.info/json/servers";getList();}
        };

        req.send();
    }

    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})
    }

    function getStats() {
        //console.log("getStats")

        var req = new XMLHttpRequest();
        req.open("get", serverUrl+"/json/stats",true);
        req.setRequestHeader('User-Agent',_useragent);
        req.onreadystatechange = function () {
            //console.log("XMLHTTPREQUEST READYSTATE: "+req.readyState + " STATUS: "+req.status)
            if (req.readyState === 4 && req.status === 200) {
                //console.log("STATUS:"+req.status)
                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}
                }
            } else if (req.readyState === 4 && req.status === 502) getRandom()
        };
        req.send();
    }

    function upVote(stationuuid,returnValue) {
        var req = new XMLHttpRequest();
        var ret = false
        req.open("get", serverUrl+"/json/vote/"+stationuuid,true);
        req.setRequestHeader('User-Agent',_useragent);
        req.onreadystatechange = function () {
            //console.log("XMLHTTPREQUEST READYSTATE: "+req.readyState + " STATUS: "+req.status)
            if (req.readyState === 4 && req.status === 200) {
                var obj = req.response.split("{").pop();
                obj = JSON.parse("{"+obj)
                //console.log(obj.ok)
                if (obj.ok) {
                    //stationCount = obj.stations-obj.stations_broken
                    //tagCount = obj.tags
                    if (obj.ok) {returnValue=true;console.log(" ****** VOTED *****")} else {returnValue=false;console.log(" ****** NOT VOTED *****")}
                }
                return ret

            }
        };
        req.send();

    }


    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)
          }
        }
    }

}
