/*
 * 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 displayNotifications(callback) {
    $.post(localStorage.getItem("syncurl"), {
        username: localStorage.getItem("username"),
        key: localStorage.getItem("key"),
        action: "checknotifications"
    }, function (data) {
        if (data.status === 'OK') {
            for (var i = 0; i < data.notifications.length; i++) {
                var n = data.notifications[i];
                if (n.seen || shown_notifications.includes(n.id)) {
                    continue;
                }

                cordova.plugins.notification.local.schedule([{
                        title: n.title,
                        text: n.content,
                        actions: [
                            {id: 'mark_read', title: "Mark Read"}
                        ],
                        id: n.id,
                        lockscreen: !n.sensitive
                    }]);

                shown_notifications.push(n.id);
            }
        }
        if (typeof callback == 'function') {
            callback();
        }
    }, "json").fail(function () {
        if (typeof callback == 'function') {
            callback();
        }
    });
}

function initForegroundNotifications() {
    cordova.plugins.notification.local.setDefaults({
        led: true,
        color: '#2196F3',
        vibrate: true,
        smallIcon: "res://ic_notification"
    });
    cordova.plugins.notification.local.on("mark_read", function (notification) {
        $.post(localStorage.getItem("syncurl"), {
            username: localStorage.getItem("username"),
            key: localStorage.getItem("key"),
            password: localStorage.getItem("password"),
            action: "readnotification",
            id: notification.id
        });
    });

    setInterval(displayNotifications, 30 * 1000);
    if (typeof cordova.plugins.notification.local.launchDetails === 'undefined') {
        displayNotifications();
    }
}

function initBackgroundNotifications() {
    var BackgroundFetch = window.BackgroundFetch;

    // Your background-fetch handler.
    var fetchCallback = function () {
        console.log('[js] BackgroundFetch event received');
        displayNotifications(function () {
            BackgroundFetch.finish();
        });
    };

    var failureCallback = function (error) {
        console.log('- BackgroundFetch failed', error);
    };

    BackgroundFetch.configure(fetchCallback, failureCallback, {
        minimumFetchInterval: 1,
        stopOnTerminate: false,
        startOnBoot: true,
        forceReload: false,
        enableHeadless: true
    });
}

function initNotifications() {
    initForegroundNotifications();
    initBackgroundNotifications();
}