/*
 * index.js
 *
 * Copyright (c) CorvusGPS.com, 2015. All rights reserved.
 */

// some global variables
var index = {
    viewModel: null
};

(function () {
    "use strict";

    /**
     * Handles the app's "pause" event. The app has been suspended. This function should save the app state.
     */
    function onPause() {
        console.log("index.js/onPause()");
        // if there is a valid viewmodel for the page, then it will be converted to a plain JavaScript object
        // and will be serialized into a JSON string and will be persisted in the HTML5 local storage
        window.localStorage.setItem("isCleanStartup", false);
        if (typeof (index.viewModel) !== "undefined" && index.viewModel != null) {
            var indexViewState = ko.toJS(index.viewModel);
            var indexViewStateJson = JSON.stringify(indexViewState);
            window.localStorage.setItem("indexViewState", indexViewStateJson);
            window.localStorage.setItem(
                "lastMapState",
                JSON.stringify({
                    center: corvusGpsMapping.getCurrentCenter(),
                    zoom: corvusGpsMapping.getCurrentZoomLevel()
                }));
            index.viewModel.suspendCurrentTimers();
        }
    };

    /**
     * Handles the app's "resume" event. The app has been reactivated. This function should restore the app state.
     */
    function onResume() {
        console.log("index.js/onResume()");
        // prevents screen timeout
        window.plugins.insomnia.keepAwake();
        // performs re-authentication
        corvusGps.refreshLogin();

        // restores the suspended timers
        if (typeof (index.viewModel) !== "undefined" && index.viewModel != null) {
            index.viewModel.restoreCurrentTimers();
        }
    };

    /**
     * Handles the "backbutton" event.
     * 
     * @param {Object} e Event source.
     */
    function onBackKeyDown(e) {
        // doesn't do the default action, no way, never, ever, it's quite unpredictable
        e.preventDefault();
        if ($("#menuModal").hasClass("modal") && $("#menuModal").hasClass("active")) {
            // if the modal dialog is opened, closes it
            ($("#menuModal")).toggleClass("active");
        }
        else {
            window.localStorage.setItem("isCleanStartup", true);
            if (typeof (index.viewModel) !== "undefined" && index.viewModel != null) {
                index.viewModel.suspendCurrentTimers();
            }
            
            // otherwise closes the app
            navigator.app.exitApp();
        }
    }

    /**
     * Handles the "offline" event, when an application goes offline, and the device is not connected to the Internet.
     */
    function onOffline() {
        // TODO: handle offline event
        console.log("index.js/onOffline(): Network connectivity has been lost!");
        // in case of losing the network connectivity stops the auto update functionalities
        if (typeof (index.viewModel) !== "undefined" && index.viewModel != null) {
            index.viewModel.suspendCurrentTimers();
        }
    }

    /**
     * Handles the "online" event, when an application goes online, and the device becomes connected to the Internet.
     */
    function onOnline() {
        // TODO: Handle the online event
        console.log("index.js/onOnline(): Network connectivity has been restored.");
        // performs re-authentication
        corvusGps.refreshLogin();

        // when the network connectivity has been restored, restores the timers as well
        if (typeof (index.viewModel) !== "undefined" && index.viewModel != null) {
            index.viewModel.restoreCurrentTimers();
        }
    }

    /**
     * Handles the app's "deviceready" event. The Cordova specific initialization should take place here.
     */
    function onDeviceReady() {
        document.addEventListener("pause", onPause.bind(this), false);
        document.addEventListener("resume", onResume.bind(this), false);

        document.addEventListener("backbutton", onBackKeyDown.bind(this), false);
        document.addEventListener("offline", onOffline.bind(this), false);
        document.addEventListener("online", onOnline.bind(this), false);

        // prevents screen timeout
        window.plugins.insomnia.keepAwake();
    };

    document.addEventListener("deviceready", onDeviceReady.bind(this), false);
})();