var SimplePush = function () {

    // Get the endpoint from localstorage (if pressent)
    var endpoint = localStorage.endpoint || null;

    // Register to request an endpoint
    var subscribe = function (cb) {
        if (!navigator.push) {
            cb("no push");

        }

        var request = navigator.push.register();
        request.onsuccess = function onSuccess() {
            // We got the endpoint, now we need to tell
            // the 3rd party service that can reach us
            // through that enpoint
            endpoint = request.result;
            Settings.setDeviceId(endpoint);
            console.log(endpoint);
        };

        request.onerror = function onError(e) {
            cb('Error registering ' + JSON.stringify(e));
        };
    };

    // Unregister for stopping any notifications
    var unsubscribe = function (cb) {
        Settings.deleteDeviceId();
    };

    return {
        'subscribe': subscribe,
        'unbsubscribe': unsubscribe
    };
}();
// Listen to push notifications
window.navigator.mozSetMessageHandler('push', function onPush(evt) {
    var channel = evt.pushEndpoint;
    var headerId = evt.version;

    app.Services.NotificationService.getNotification(function(data) {
        Notifications.notify(data);
    }, headerId);
});


window.navigator.mozSetMessageHandler('push-register', function (e) {
    console.log('push-register received, I need to register my endpoint(s) again!');

    var req = navigator.push.register();
    req.onsuccess = function(e) {
        var endpoint = req.result;
        if (endpoint != Settings.getDeviceId()) {
            app.Services.NotificationService.updateDeviceId(endpoint);
        }
    };

    req.onerror = function(e) {
        console.error("Error getting a new endpoint: " + JSON.stringify(e));
    };
});


// Automatically register if not register previously
if (!Settings.getDeviceId()) {
    SimplePush.subscribe(function onSubscribe(err, data) {
        if (err) {
            alert(err);
        }

        console.log('Subscribed :: ' + JSON.stringify(data));
    });
}