/*
 * uNav http://launchpad.net/unav
 * Copyright (C) 2015 JkB https://launchpad.net/~joergberroth
 * Copyright (C) 2015 Marcos Alvarez Costales https://launchpad.net/~costales
 *
 * uNav is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * uNav is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
// Thanks http://askubuntu.com/questions/352157/how-to-use-a-sqlite-database-from-qml


function openDB() {
    var db = LocalStorage.openDatabaseSync("storedkeys_db", "0.1", "Stored Authenticator Keys", 1000);
    try {
        db.transaction(function(tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS storedkeys( added DATE, identifier INTEGER PRIMARY KEY, keyJSON TEXT, description TEXT )');
        });
    } catch (err) {
        console.log("Error creating table in database: " + err)
    } return db
}

function storeKey(added, keyJSON, description) {
    var db = openDB();
    db.transaction(function(tx){
        tx.executeSql('INSERT OR REPLACE INTO storedkeys (added, keyJSON, description) VALUES(?, ?, ?)', [added, keyJSON, description]);
    });
}

function updateStoredKey(id, modified, url, desc) {
    var db = openDB();

    db.transaction(function(tx){
        tx.executeSql('UPDATE storedkeys SET added=?, keyJSON=?, description=? WHERE identifier=?;', [modified, url, desc, id]);
    });
}

function getKeys() {
    var db = openDB();
    var rs;
    db.transaction(function(tx) {
        rs = tx.executeSql('SELECT * FROM storedkeys');
    });

    return rs
}

function findKey(key) {
    var db = openDB();
    var rs;
    db.transaction(function(tx) {
        rs = tx.executeSql('SELECT * FROM storedkeys WHERE keyJSON like ?;', [key]);
    });

    if (rs.rows.length > 0) {
        return true;
    } else {
        return false;
    }
}

function deleteKey(id){
    console.log("Deleting register id: " + id);
    var db = openDB();
    db.transaction(function(tx){
        tx.executeSql('DELETE FROM storedkeys WHERE identifier=?;', [id]);
    });
}

function updateCounter(id, difference){
    var db = openDB();
    var countString = "";
    var updatedUrl = "";

    db.transaction(function(tx){
        var rs = tx.executeSql('SELECT * FROM storedkeys WHERE identifier=?;', [id]);
        if (rs.rows.length > 0) {
            var url = rs.rows.item(0).keyJSON;
            countString = url.match(/counter=(.*?)\&/);
            if (!countString) countString = url.match(/counter=(.*?)$/)[0];

            //Check if last char is &
            if (countString.slice(-1) == "&") countString = countString.slice(0,-1);

            var counterValue = Number(countString.slice(8)) + difference;
            url = url.replace(countString, "counter=" + counterValue.toString());
            updatedUrl = url;

            tx.executeSql('UPDATE storedkeys SET keyJSON=? WHERE identifier=?;', [url, id]);

        } else console.log("Error: Key url db is empty");
    });

    return updatedUrl;
}
