/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */


function gatherSyncData() {
    if (getStorage("syncstateversion") == null) {
        setStorage("syncstateversion", 0);
    }
    var data = {
        localStorage: {},
        stateversion: getStorage("syncstateversion") == null ? 0 : getStorage("syncstateversion")
    };
    var allitems = getAllStorage();
    for (var i = 0; i < allitems.length; i++) {
        var key = allitems[i].key;
        var value = allitems[i].value;
        if (SETTINGS.synckeyblacklist.includes(key)) {
            continue;
        }
        data.localStorage[key] = value;
    }
    return data;
}

function syncDataToLocalStorage(data, stateversion) {
    for (var key in data.localStorage) {
        if (data.localStorage.hasOwnProperty(key)) {
            setStorage(key, data.localStorage[key], true);
        }
    }
    setStorage("syncstateversion", stateversion);
}

function resolveSync(remotedata, remotestateversion) {
    var localstateversion = getStorage("syncstateversion");
    console.log("Resolving sync: remote state: " + remotestateversion, "local state: " + localstateversion);
    if (localstateversion == remotestateversion) {
        // Server and client both have same version
        console.log("Sync: server is same as client");
        return true;
    } else if (Number(localstateversion) < Number(remotestateversion)) {
        // Server has newer version
        console.log("Sync: server is newer than client");
        syncDataToLocalStorage(remotedata, remotestateversion);
        return true;
    } else {
        // We have the newer version
        console.log("Sync: client is newer than server.");
        return true;
    }
    return false;
}

function syncNow(callback) {
    var username = getStorage("username");
    var password = getStorage("password");
    if (username == null || password == null) {
        return false;
    }
    var data = gatherSyncData();

    $.post(SETTINGS.syncapi, {
        username: username,
        password: password,
        data: JSON.stringify(data),
        stateversion: data.stateversion
    }, function (resp) {
        if (resp.status == "OK") {
            resolveSync(resp.data, resp.stateversion);
            setStorage("lastsync", Date.now() / 1000);
            if (typeof callback == "function") {
                callback();
            }
        }
    }, "json");
    return true;
}

function loadSettings() {
    applyColorTheme();
    setAnimations();

    if (platform_type == "cordova") {
        if (getStorage("wakelock") == "true") {
            window.powerManagement.acquire(function () {
                console.log("Info", 'Wakelock acquired');
            }, function () {
                console.log("Warn", 'Failed to acquire wakelock');
            });
        } else {
            window.powerManagement.release(function () {
                console.log("Info", 'Wakelock released');
            }, function () {
                console.log("Warn", 'Failed to release wakelock');
            });
        }

//        if (getStorage("runinbackground") == "true") {
//            cordova.plugins.foregroundService.start('PackageHelper', 'GPS active');
//        } else {
//            cordova.plugins.foregroundService.stop();
//        }
    }
}

syncNow(loadSettings);

// Sync every two minutes
setInterval(function () {
    syncNow(loadSettings);
}, 1000 * 60 * 2);