/*
 * 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 checkAndSave(username, password) {
    app.preloader.show();

    callAPI("ping", {
        username: username,
        password: password
    }, function (data) {
        localStorage.setItem("username", username);
        localStorage.setItem("password", password);
        localStorage.setItem("configured", true);
        callAPI("playerexists", {
            username: username,
            password: password
        }, function (resp) {
            app.preloader.hide();
            if (resp.exists == true) {
                router.navigate("/home");
            } else {
                router.navigate("/chooseteam");
            }
        }, function (msg) {
            app.preloader.hide();
            app.dialog.alert(msg, "Error");
        });
    }, function (msg) {
        app.preloader.hide();
        app.dialog.alert(msg, "Error");
    });
}

$(".type-card").click(function () {
    app.preloader.show();
    callAPI("createplayer", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password"),
        team: $(this).data("id")
    }, function (success) {
        app.preloader.hide();
        router.navigate("/home");
    }, function (msg) {
        app.preloader.hide();
        app.dialog.alert(msg, "Error");
    });
});

function setupAccount() {
    var username = $("#username").val();
    var password = $("#password").val();

    checkAndSave(username, password);
}