/*
 * 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 historyctr = -1;
/**
 * Open an app with native Android UI elements
 * @param String api Path to the mobile API
 * @param String url Base URL of the app
 * @param String icon URL to the app icon
 * @param String title Friendly app name
 * @returns {undefined}
 */
function launchapp(api, url, icon, title) {
    app.dialog.progress("Loading...").setText(title);

    router.navigate({
        name: 'app'
    });
    $.post(url + api, {
        username: localStorage.getItem("username"),
        key: localStorage.getItem("key"),
        password: localStorage.getItem("password"),
        action: "start_session"
    }, function (data) {
        if (data.status === 'OK') {
            $('#appframe').on("load", function () {
                app.dialog.close();
                historyctr++;
                // Do this right away so it's a bit harder to glitch
                $('#appframe').contents().find('.navbar-right').html("<li><a onclick='quitapp()'><i class='fas fa-sign-out-alt fa-fw'></i> Back to Menu</a></li>");

                $.get("js/polyfills.js", function (script) {
                    $('#appframe').contents().find('body').append("<script>" + script + "<\/script>");
                    $.get("vendor/js/jquery-ui.min.js", function (script) {
                        $('#appframe').contents().find('body').append("<script>" + script + "<\/script>");
                        $.get("vendor/js/hammer.min.js", function (script) {
                            $('#appframe').contents().find('body').append("<script>" + script + "<\/script>");
                            $.get("js/app-inject.js", function (script) {
                                script = script.replace("__USERNAME__", userinfo.realname);
                                script = script.replace("__LOGO__", icon);
                                $('#appframe').contents().find('body').append("<script>" + script + "<\/script>");
                            });
                        });
                    });
                });
            });
            $('#appframe').attr('src', url);
        } else {
            navigator.notification.alert(data.msg, null, "Error", 'Dismiss');
            router.back();
        }
    }, "json").fail(function () {
        navigator.notification.alert("Could not connect to the server.  Try again later.", null, "Error", 'Dismiss');
        router.back();
    });
}

function navigateApp(src) {
    $('#appframe').attr('src', './' + src);
}

var scanningactive = false;
var dedup = [];
window.addEventListener('message', function (event) {
    console.log("app event: " + event.data);
    setTimeout(function () {
        dedup = [];
    }, 500);
    if (dedup.includes(event.data)) {
        return;
    }
    dedup.push(event.data);
    if (event.data == "quit") {
        router.back();
        if (cordova.platformId == 'android') {
            StatusBar.backgroundColorByHexString("#1976d2");
        } else {
            StatusBar.backgroundColorByHexString("#2196f3");
        }
    } else if (event.data == "done_loading") {
        app.dialog.close();
    } else if (event.data == "goneback") {
        historyctr -= 1;
    } else if (event.data.startsWith("load_css ")) {
        var nav_breakpoint = event.data.split(" ", 2)[1];
        $.get("css/app-inject.css", function (style) {
            var break_px = "767";
            switch (nav_breakpoint) {
                case "sm":
                    break_px = "575";
                    break;
                case "md":
                    break_px = "767";
                    break;
                case "lg":
                    break_px = "991";
                    break;
                case "xl":
                    break_px = "1199";
                    break;
            }
            style = style.replace("max-width: 767px", "max-width: " + break_px + "px");
            $('#appframe').contents().find('head').append("<style>" + style + "</style>");
        });
    } else if (event.data.startsWith("setcolor ")) {
        var color = event.data.split(" ", 2)[1];
        if (cordova.platformId == 'android') {
            window.plugins.headerColor.tint(color);
            for (var swatch in _PALETTE) {
                if (color == _PALETTE[swatch]["shade_500"]) {
                    StatusBar.backgroundColorByHexString(_PALETTE[swatch]["shade_700"]);
                    return;
                }
            }
            StatusBar.backgroundColorByHexString(shadeColor2(color, -0.1));
        } else {
            StatusBar.backgroundColorByHexString(color);
        }
    } else if (event.data.startsWith("scancode ")) {
        var callbackcode = event.data.split(" ").slice(1).join(" ");
        console.log("got scancode " + callbackcode);
        try {
            if (scanningactive) {
                console.log("Scanner already active, ignoring request.");
                return;
            }
            scanningactive = true;
            cordova.plugins.barcodeScanner.scan(
                    function (result) {
                        scanningactive = false;
                        if (!result.cancelled) {
                            var iframe = document.getElementById("appframe");
                            iframe.contentWindow.postMessage("coderesult~|~" + callbackcode + "~|~" + result.text, "*");
                        }
                    },
                    function (error) {
                        scanningactive = false;
                        navigator.notification.alert("Scanning failed: " + error, null, "Error", 'Dismiss');
                    },
                    {
                        "showFlipCameraButton": true,
                        "prompt": "Scan Code"
                    }
            );
        } catch (ex) {
            scanningactive = false;
            navigator.notification.alert(ex.message, null, "Error", 'Dismiss');
        }
    }
}, false);