import QtQuick 2.0
import QtQuick.XmlListModel 2.0

Item {
    property bool running: true
    property string filter: ""
    property alias countryModel: countryModel
    property alias source: xmlModel.source

    function addtomodel(){
        countryModel.clear()
        var cname
        var filt
        for(var i = 0; i < xmlModel.count; i++) {
            cname = getCountryName(xmlModel.get(i).name)
            //if (cname) filt = cname.toLowerCase()
            if (cname) {filt = cname.toLowerCase(); if (filt.indexOf(filter) !== -1) countryModel.append({"name" : cname, "alpha_2" : xmlModel.get(i).name,"stationcount" : xmlModel.get(i).stationcount})}
            //console.log(cname)
        }
        countryModel.listModelSort(countryModel, compareElements)
        //numberOfCountries = i
        countryCount = countryModel.count
     //   console.log("COUNTRIESMODEL DONE: "+countryModel.count)
        running = false
    }

    function compareElements(elem1, elem2) {
        return elem1.name.localeCompare(elem2.name)
    }

    ListModel {
        id: countryModel
        function listModelSort(listModel, compareFunc) {
            var indexes = new Array(listModel.count);
            for (var i = 0; i < listModel.count; i++) indexes[i] = i;
            indexes.sort(function (indexA, indexB) { return compareFunc(get(indexA), get(indexB)) } );
            var sorted = 0;
            while (sorted < indexes.length && sorted === indexes[sorted]) sorted++;
            if (sorted === indexes.length) return;
            for (i = sorted; i < indexes.length; i++) {
                var idx = indexes[i];
                listModel.move(idx, listModel.count - 1, 1);
                listModel.insert(idx, { } );
            }
            listModel.remove(sorted, indexes.length - sorted);
        }
    }

    XmlListModel {
            id: xmlModel
            query: "/result/countrycode"
            //source: radioServers.serverUrl + type + "/countrycodes?hidebroken=true"

            XmlRole { name: "name"; query: "@name/string()" }
            XmlRole { name: "stationcount"; query: "@stationcount/string()" }

            onStatusChanged: {
                //if (status === XmlListModel.Loading) loadingInfo = "Preloading countries"
                if (status === XmlListModel.Ready) {
                    addtomodel()
                    running = false
                }
                //if (status === XmlListModel.Loading) running = true;
            }
        }

    onFilterChanged: addtomodel()
}