/*
 * 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() {
    var data = {
        localStorage: {},
        changed: getStorage("lastchange") == null ? 0 : getStorage("lastchange"),
    };
    if (!inStorage("lastsync")) {
        // first time syncing to the server, let's make sure
        // the server settings take precedence
        data.changed = 1;
    }
    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) {
    for (var key in data.localStorage) {
        if (data.localStorage.hasOwnProperty(key)) {
            setStorage(key, data.localStorage[key], true);
        }
    }
}

function resolveSync(remotedata) {
    var localchangetime = getStorage("lastchange");
    if (remotedata.changed == null) {
        // The server has nothing, this is the first sync
        return true;
    }
    if (localchangetime == null) {
        // No local setting changes but since we've gotten this far,
        // the server has stuff for us
        syncDataToLocalStorage(remotedata);
        return true;
    }
    if (localchangetime < remotedata.changed) {
        // The server has newer stuff for us
        syncDataToLocalStorage(remotedata);
        return true;
    }
    if (localchangetime >= remotedata.changed) {
        // Our local data is newer or the same as the server copy
        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)
    }, function (resp) {
        if (resp.status == "OK") {
            resolveSync(resp.data);
            setStorage("lastsync", Date.now() / 1000);
            if (typeof callback == "function") {
                callback();
            }
        }
    }, "json");
    return true;
}

function loadSettings() {
    applyColorTheme();

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