var db = undefined;
var newStation = false

function settings_db_open() {
    if (db === undefined)
        db = LocalStorage.openDatabaseSync("harbour-allradio-2", "2.0", "Database", 100000);
    return db;
}

function checkforold() {
    db = settings_db_open();
        try {
            db.transaction(function(tx)
            {
                var rs = tx.executeSql('SELECT * FROM channels');
              //  console.log("OLD DATABSE TABLE EXISTS")
            });
        }
        catch(a)
        {
            //    console.log("NO OLD DATABASE")
        }
    }

function init() {
    db = settings_db_open();
    checkforold()
    try {
        db.transaction(
            function(tx) {
                //tx.executeSql('CREATE TABLE IF NOT EXISTS settings(setting TEXT UNIQUE, value TEXT)');
                tx.executeSql('CREATE TABLE IF NOT EXISTS stations (id TEXT UNIQUE, name TEXT, countrycode STRING, homepage TEXT, radiourlresolved TEXT, favicon TEXT, tagslist TEXT, codec TEXT, bitrate TEXT, hls TEXT, myclicktimestamp STRING, myclickcount INTEGER, favorite INTEGER)');
                tx.executeSql('CREATE TABLE IF NOT EXISTS countries (countrycode TEXT UNIQUE, myclickcount INTEGER)');
                tx.executeSql('CREATE TABLE IF NOT EXISTS tags (tag TEXT UNIQUE, myclickcount INTEGER)');
            }
        );
    }
    catch(a)
    {
        console.log("create failed: "+a)
        return false
    }
}
// id TEXT UNIQUE, name TEXT, countrycode STRING, homepage TEXT, radiourlresolved TEXT, favicon TEXT, tagslist TEXT, codec TEXT, bitrate TEXT, hls TEXT, myclicktimestamp STRING, myclickcount INTEGER, favorite INTEGER
// UPDATE OR INSERT STATION CLICKED
function setStationClicked(myclicktimestamp,id,name,countrycode,homepage,radiourlresolved,favicon,tagslist,codec,bitrate,hls,favorite) {
    db = settings_db_open();
    var cc
    var t
    var fav
    if (countrycode === "") cc = "No Country"; else cc = countrycode
    if (tagslist === "") t = "NoTag"; else t = tagslist
    if (favorite === true) fav = 1; else fav = 0
    try {
        db.transaction(function(tx) {
        var rs = tx.executeSql('UPDATE stations SET myclicktimestamp="'+myclicktimestamp+'",favorite='+fav+',myclickcount=myclickcount+1 WHERE id="'+id+'"');
            if (rs.rowsAffected > 0) {
            //    console.log("DB UPDATE STATION CLICK: "+id)
            } else {
                tx.executeSql('INSERT INTO stations VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',[id, name, cc, homepage, radiourlresolved,favicon,t,codec,bitrate,hls,myclicktimestamp,1,fav]);
           //     console.log("DB INSERT STATION CLICK: "+id)
            }
        }
        );
        setCountryClicked(cc)
        setTagClicked(t)
    }
    catch(a)
    {
        console.log("ERROR SETSTATIONCLICKED: "+a)
    }
}
// GET LIMIT NUMBER OF RECENT CLICKED TO MODEL
function getStationRecentClicked(model,limit)
{
    db = settings_db_open();
    try {
        db.transaction(function(tx)
        {
            model.clear()
            var rs = tx.executeSql('SELECT * FROM stations ORDER BY myclicktimestamp DESC LIMIT ?',limit);
            for(var i = 0; i < rs.rows.length; i++) {
                model.append({"stationuuid" : rs.rows.item(i).id, "name" : rs.rows.item(i).name, "countrycode" : rs.rows.item(i).countrycode,"homepage" : rs.rows.item(i).homepage,"url_resolved": rs.rows.item(i).radiourlresolved,"favicon":rs.rows.item(i).favicon,
                                 "tags":rs.rows.item(i).tagslist,"codec":rs.rows.item(i).codec, "bitrate":rs.rows.item(i).bitrate,"hls":rs.rows.item(i).hls,"lastcheckok": "1","favorite": rs.rows.item(i).favorite})
            }
            return true
        });
    }
    catch(a)
    {
        console.log("FAVO STATION RESENT failed: "+a);
        return false;
    }
}
function getFavorites(model,sort,limit) // name, myclickcount,myclicktimestamp
{
    var reverse = sort === "name" ? "ASC" : "DESC"
    db = settings_db_open();
    try {
        db.transaction(function(tx)
        {
            model.clear()
            var rs = tx.executeSql('SELECT * FROM stations WHERE favorite=1 ORDER BY '+sort+' '+reverse+' LIMIT '+limit);
            for(var i = 0; i < rs.rows.length; i++) {
                model.append({"stationuuid" : rs.rows.item(i).id, "name" : rs.rows.item(i).name, "countrycode" : rs.rows.item(i).countrycode,"homepage" : rs.rows.item(i).homepage,"url_resolved": rs.rows.item(i).radiourlresolved,"favicon":rs.rows.item(i).favicon,
                                 "tags":rs.rows.item(i).tagslist,"codec":rs.rows.item(i).codec, "bitrate":rs.rows.item(i).bitrate,"hls":rs.rows.item(i).hls,"lastcheckok": "1","favorite": rs.rows.item(i).favorite})
            }
            return true
        });
    }
    catch(a)
    {
        console.log("FAVO STATION MOST PLAYED failed: "+a);
        return false;
    }
}
function getHistory(model,limit)
{
    db = settings_db_open();
    try {
        db.transaction(function(tx)
        {
            model.clear()
            var rs = tx.executeSql('SELECT * FROM stations ORDER BY myclicktimestamp DESC LIMIT ?',limit);
            for(var i = 0; i < rs.rows.length; i++) {
                model.append({"stationuuid" : rs.rows.item(i).id, "name" : rs.rows.item(i).name, "countrycode" : rs.rows.item(i).countrycode,"homepage" : rs.rows.item(i).homepage,"url_resolved": rs.rows.item(i).radiourlresolved,"favicon":rs.rows.item(i).favicon,
                                 "tags":rs.rows.item(i).tagslist,"codec":rs.rows.item(i).codec, "bitrate":rs.rows.item(i).bitrate,"hls":rs.rows.item(i).hls,"lastcheckok": "1","favorite": rs.rows.item(i).favorite})
            }
            return true
        });
    }
    catch(a)
    {
        console.log("FAVO STATION MOST PLAYED failed: "+a);
        return false;
    }
}
function getMostPlayedFavorites(model,limit)
{
    db = settings_db_open();
    try {
        db.transaction(function(tx)
        {
            model.clear()
            var rs = tx.executeSql('SELECT * FROM stations WHERE favorite=1 ORDER BY myclickcount DESC LIMIT ?',limit);
            for(var i = 0; i < rs.rows.length; i++) {
                model.append({"stationuuid" : rs.rows.item(i).id, "name" : rs.rows.item(i).name, "countrycode" : rs.rows.item(i).countrycode,"homepage" : rs.rows.item(i).homepage,"url_resolved": rs.rows.item(i).radiourlresolved,"favicon":rs.rows.item(i).favicon,
                                 "tags":rs.rows.item(i).tagslist,"codec":rs.rows.item(i).codec, "bitrate":rs.rows.item(i).bitrate,"hls":rs.rows.item(i).hls,"lastcheckok": "1","favorite": rs.rows.item(i).favorite})
            }
            return true
        });
    }
    catch(a)
    {
        console.log("FAVO STATION MOST PLAYED failed: "+a);
        return false;
    }
}
function setStationFavorite(id,name,countrycode,homepage,radiourlresolved,favicon,tagslist,codec,bitrate,hls,favorite) {
    db = settings_db_open();
    var cc
    var t
    var fav
  //  console.log("FAVORITE = "+favorite)
    if (countrycode === "") cc = "No Country"; else cc = countrycode
    if (tagslist === "") t = "NoTag"; else t = tagslist
    if (favorite === true) fav = 1; else fav = 0
    try {
        db.transaction(function(tx) {
        var rs = tx.executeSql('UPDATE stations SET favorite='+fav+' WHERE id="'+id+'"');
            if (rs.rowsAffected > 0) {
             //   console.log("DB UPDATE STATION CLICK: "+fav+" - "+id)
            } else {
                tx.executeSql('INSERT INTO stations VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',[id, name, cc, homepage, radiourlresolved,favicon,t,codec,bitrate,hls,"",1,fav]);
            //    console.log("DB INSERT STATION CLICK: "+id)
            }
        }
        );
    }
    catch(a)
    {
        console.log("ERROR SET FAVORITE: "+a)
    }
}
// get if favorite
// get if favorite
function getStationFavorite(id) { // Get info about number of clicks and if station is a favorite
    //model.clear()
    var db = settings_db_open();
    var res = 0;
    try {
       db.transaction(function(tx) {
           var rs = tx.executeSql('SELECT * FROM stations WHERE id = "'+id+'" AND favorite = 1');
           res = rs.rows.length
      //     console.log("FAVO RESULT: "+res+" ID: "+id )
           if (res>0) return true; else return false;


       })
    } catch (err) {
       res = 0
        console.log("ERROR ON FAVORITE CHECK: "+err)
        return false
    };
    return res
}
function setCountryClicked(countrycode) {
    db = settings_db_open();
   // var clicks = getCountryClick(countrycode) + 1
    try {
        db.transaction(function(tx) {
            var rs = tx.executeSql('UPDATE countries SET myclickcount=myclickcount+1 WHERE countrycode="'+countrycode+'"');
            if (rs.rowsAffected > 0) {
         //       console.log("DB UPDATE COUNTRY CLICK: "+countrycode)
            } else {
                tx.executeSql('INSERT INTO countries VALUES (?,?);', [countrycode, 1]);
            //    console.log("DB INSERT COUNTRY CLICK: "+countrycode)
            }
            }
        );
    }
    catch(a)
    {
        console.log("Failed setCountryClicked: "+a)
        return false
    }
}
function getCountryRecentClicked(model,limit)
{
    db = settings_db_open();
    try {
        db.transaction(function(tx)
        {
            model.clear()
            var rs = tx.executeSql('SELECT * FROM countries ORDER BY myclickcount DESC LIMIT '+limit);
            for(var i = 0; i < rs.rows.length; i++) {
                model.append({"alpha_2" : rs.rows.item(i).countrycode})
            }
            return true
        });
    }
    catch(a)
    {
        console.log("FAVO COUNTRY failed: "+a);
        return false;
    }
}
function setTagClicked(tagslist) {
    db = settings_db_open();
    var tags = tagslist.split(",")
    //var tempTag
    try {
        db.transaction(function(tx) {
            for(var i = 0; i < tags.length; i++) {
                var rs = tx.executeSql('UPDATE tags SET myclickcount=myclickcount+1 WHERE tag="'+tags[i]+'"');
                if (rs.rowsAffected > 0) {
         //           console.log("DB UPDATE TAG CLICK: "+tags[i])
                } else {
                    tx.executeSql('INSERT INTO tags VALUES (?,?);', [tags[i], 1]);
           //         console.log("DB INSERT TAG CLICK: "+tags[i])
                }
            }
        }
        );
    }
    catch(a)
    {
        console.log("Failed settagsclicked: "+a)
        return false
    }
}
function getTagsRecentClicked(model,limit)
{
    db = settings_db_open();
    //var max = 0
    try {
        db.transaction(function(tx)
        {
            model.clear()
            var rs = tx.executeSql('SELECT * FROM tags ORDER BY myclickcount DESC limit '+limit);
            for(var i = 0; i < rs.rows.length; i++) {
                if (rs.rows.item(i).tag !== "NoTag") {
                    model.append({"tag" : rs.rows.item(i).tag,"myclickcount" : rs.rows.item(i).myclickcount})
                }
               // if (rs.rows.item(i).myclickcount > max) max = rs.rows.item(i).myclickcount
            }
           // radioPlayer.maxTagClicks = max
         //   console.log("MAX TAGS: "+max)
            return true
        });


    }
    catch(a)
    {
        console.log("FAVO TAGS failed: "+a);
        return false;
    }
}
function getTagsClicked(model,limit)
{
    db = settings_db_open();
    var max = 0
    try {
        db.transaction(function(tx)
        {
            model.clear()
            var rs = tx.executeSql('SELECT * FROM tags ORDER BY tag limit '+limit);
            for(var i = 0; i < rs.rows.length; i++) {
                if (rs.rows.item(i).tag !== "NoTag") {
                    model.append({"tag" : rs.rows.item(i).tag,"myclickcount" : rs.rows.item(i).myclickcount})
                    if (rs.rows.item(i).myclickcount > max) max = rs.rows.item(i).myclickcount
                }
            }
           // radioPlayer.maxTagClicks = max
            console.log("MAX TAGS: "+max)
            maxTags = max
            return true
        });


    }
    catch(a)
    {
        console.log("FAVO TAGS failed: "+a);
        return false;
    }
}
