/*
 * 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 getNotifications(callback) {
    var notifications = [];
    $.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];
                notifications.push({
                    id: n.id,
                    title: n.title,
                    text: n.content,
                    sensitive: n.sensitive,
                    seen: n.seen
                });
            }
            callback(notifications);
            return;
        }
        if (typeof callback == 'function') {
            callback(false);
        }
    }, "json").fail(function () {
        if (typeof callback == 'function') {
            callback(false);
        }
    });
}

function displayNotifications(callback) {
    getNotifications(function (notifications) {
        if (notifications != false) {
            for (var i = 0; i < notifications.length; i++) {
                var n = notifications[i];
                if (n.seen || shown_notifications.includes(n.id)) {
                    continue;
                }

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

                shown_notifications.push(n.id);
            }
            if (typeof callback == 'function') {
                callback();
            }
            return;
        }
        if (typeof callback == 'function') {
            callback();
        }
    });
}

function deleteNotification(id) {
    $.post(localStorage.getItem("syncurl"), {
        username: localStorage.getItem("username"),
        key: localStorage.getItem("key"),
        password: localStorage.getItem("password"),
        action: "deletenotification",
        id: id
    });
}

function readNotification(id) {
    $.post(localStorage.getItem("syncurl"), {
        username: localStorage.getItem("username"),
        key: localStorage.getItem("key"),
        password: localStorage.getItem("password"),
        action: "readnotification",
        id: id
    });
}

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