/* 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/. */

var $$ = Dom7;

// Detect platform and run platform-specific setup code
// for Cordova, NW.js, or the browser
initPlatform();

Template7.global = {
    qrenabled: (platform_type == "cordova")
};

var app = new Framework7({
    root: "#app",
    name: "TerranQuest",
    id: "com.netsyms.terranquest.TerranQuest",
    theme: platform_theme,
    card: {
        swipeToClose: false
    },
    popup: {
        backdrop: false
    },
    init: true,
    initOnDeviceReady: false,
    routes: routes
});

var mainView = app.views.create('.view-main', {
    url: "/"
});

var router = mainView.router;

function restartApplication() {
    window.location = "index.html";
}

function logout() {
    localStorage.clear();
    restartApplication();
}

router.on("pageInit", function (pagedata) {
    pagedata.$el.find('script').each(function (el) {
        if ($$(this).attr('src')) {
            var s = document.createElement('script');
            s.src = $$(this).attr('src');
            $$('head').append(s);
        } else {
            eval($$(this).text());
        }
    });
});

/**
 * Check if the server is alive.
 * @param {function} callback
 * @returns {undefined}
 */
function isServerAlive(callback) {
    callAPIRawResponse("ping", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password")
    }, function (data) {
        callback(true);
    }, function (msg, xhr) {
        app.preloader.hide();
        if (xhr.status == 401) {
            callback(true);
        } else if (xhr.status == 400) {
            callback(true);
        } else {
            callback(false);
        }
    });
}

/**
 * Compare two version strings.
 * http://stackoverflow.com/a/16187766/2534036
 * @param {string} a
 * @param {string} b
 * @returns a number < 0 if a < b, a number > 0 if a > b, 0 if a = b
 */
function compareVersions(a, b) {
    var i, diff;
    var regExStrip0 = /(\.0+)+$/;
    var segmentsA = a.replace(regExStrip0, '').split('.');
    var segmentsB = b.replace(regExStrip0, '').split('.');
    var l = Math.min(segmentsA.length, segmentsB.length);

    for (i = 0; i < l; i++) {
        diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
        if (diff) {
            return diff;
        }
    }
    return segmentsA.length - segmentsB.length;
}

/**
 * Check if the saved username and password are valid.
 * @param {function} callback A function that will be called with a boolean argument indicating validity.
 * @return {undefined}
 */
function checkLogin(callback) {
    if (localStorage.getItem("username") === null || localStorage.getItem("password") === null) {
        callback(false);
        return;
    }

    callAPI("ping", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password")
    }, function (data) {
        callback(true);
    }, function (msg) {
        callback(false);
    });
}

if (localStorage.getItem("configured") == null) {
    router.navigate("/signin");
} else {
    isServerAlive(function (yes) {
        if (yes) {
            callAPI("version", {
                username: localStorage.getItem("username"),
                password: localStorage.getItem("password")
            }, function (data) {
                $.getJSON("package.json", {}, function (local) {
                    if (compareVersions(local.version, data.version) < 0) {
                        router.navigate("/upgrade");
                    } else {
                        checkLogin(function (valid) {
                            if (valid) {
                                callAPI("playerexists", {
                                    username: localStorage.getItem("username"),
                                    password: localStorage.getItem("password")
                                }, function (resp) {
                                    if (resp.exists == true) {
                                        router.navigate("/home");
                                    } else {
                                        router.navigate("/chooseteam");
                                    }
                                }, function (msg) {
                                    router.navigate("/signin");
                                });
                            } else {
                                router.navigate("/signin");
                            }
                        });
                    }
                });
            });
        } else {
            router.navigate("/connection");
        }
    });
}