/*
 * 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 compiledPages = {};
var pagesToCompile = [
    "home",
    "welcome",
    "appointment",
    "dropandsend",
    "rateresult",
    "account",
    "trackresult",
    "settings"
];
console.log("Compiling page templates...");
for (var i = 0; i < pagesToCompile.length; i++) {
    compiledPages[pagesToCompile[i]] = Template7.compile($.ajax({
        type: "GET",
        url: "./pages/" + pagesToCompile[i] + ".html",
        async: false
    }).responseText);
}
console.log("Compiled page templates.");

var routes = [
    {
        path: '/welcome',
        content: compiledPages.welcome(),
        name: 'welcome',
        on: {
            pageAfterIn: function () {

            }
        }
    },
    {
        path: '/home',
        name: 'home',
        on: {
            pageBeforeIn: function () {
                // make sure it's not shown right after account setup
                var accountsetup = (inStorage("accountkey") && inStorage("phonenumber"));
                if (accountsetup) {
                    $("#finishaccountsetupnag").css("display", "none");
                }
            }
        },
        async: function ( { resolve, reject }) {
            // Show a nag message if no account is set up
            var accountsetup = (inStorage("accountkey") && inStorage("phonenumber")) || getStorage("hideaccountnag") == "true";
            // add escape hatch to regular website if running online
            var escapehatch = false;
            if (window.location.hostname == "app.helena.express") {
                escapehatch = true;
            }
            resolve({
                content: compiledPages.home({
                    accountsetup: accountsetup,
                    escapehatch: escapehatch,
                    pages: [
                        {
                            title: "Drop and Send",
                            href: "/dropandsend",
                            icon: "fad fa-box-alt",
                            text: "Bring your package to a secure drop location and we'll ship it for you. No postage or appointment needed."
                        },
                        {
                            title: "Book Appointment",
                            href: "/appointment",
                            icon: "fad fa-calendar-alt",
                            text: "Get mailing, shipping, and notary services on your schedule anywhere in the Helena area."
                        },
                        {
                            title: "My Account",
                            href: "/account",
                            icon: "fad fa-user-circle",
                            text: "Manage your Helena Express account and check rewards points balance."
                        }
                    ]
                })
            }, {});
        }
    },
    {
        path: '/appointment',
        name: 'appointment',
        async: function ( { resolve, reject }) {
            resolve({
                content: compiledPages.appointment({
                    services: [
                        {
                            title: "Package Pickup",
                            text: "A courier will come to you and ship your mail, packages, etc.",
                            icon: "fad fa-hand-holding-box",
                            serviceid: 19
                        },
                        {
                            title: "Mobile Notary",
                            text: "A notary public will come to you and notarize your documents.",
                            icon: "fad fa-file-signature",
                            serviceid: 21
                        }
                    ]
                })
            }, {
            });
        },
        routes: [
            {
                path: "/:serviceId",
                async: function ( { resolve, reject, to }) {
                    var url = SETTINGS.appointmenturl;
                    if ($("#app").hasClass("theme-dark")) {
                        url = SETTINGS.appointmenturl_darkmode;
                    }
                    resolve({
                        content: compiledPages.appointment({
                            url: url + "&service=" + to.params.serviceId
                        })
                    }, {
                    });
                }
            }
        ]
    },
    {
        path: '/dropandsend',
        name: 'dropandsend',
        content: compiledPages.dropandsend(),
        on: {
            pageBeforeIn: function () {
                checkIfAccountGoodWithPaymentMethod(function (ok) {
                    if (!ok) {
                        $("#addPaymentMethodNag").css("display", "");
                    }
                }, function (error) {
                    $("#addPaymentMethodNag").css("display", "");
                });
            },
            pageAfterOut: function () {
                dropboxMap = null;
            }
        }
    },
    {
        path: '/track',
        url: './pages/track.html',
        name: 'track',
        on: {
            pageBeforeIn: function () {
                addTrackingSuggestions();
                $("#trackingcode").val("0");
                app.input.validate("#trackingcode");
                $("#trackingcode").val("");
            }
        }
    },
    {
        path: '/rates',
        url: './pages/rates.html',
        name: 'rates',
        on: {
            pageAfterIn: function () {
                initRateForm();
            }
        }
    },
    {
        path: '/account',
        name: 'account',
        content: compiledPages.account(),
        on: {
            pageAfterIn: function () {
                initAccountPage();
            }
        }
    },
    {
        path: '/track/:code',
        name: 'trackresult',
        async: trackOpenAsync,
        on: {
            pageAfterIn: function () {
                var mapboxel = document.getElementById("mapbox-track");
                var trackingMap = new MapControl(mapboxel, false);
                trackingMap.reloadMap();
                var latitude = $(mapboxel).data("latitude");
                var longitude = $(mapboxel).data("longitude");
                var accurate = $(mapboxel).data("accurate") == true;
                trackingMap.clearMarkersAndCenterMapOnNewMarker("package-marker", latitude, longitude, accurate);
            }
        }
    },
    {
        path: '/credits',
        url: './pages/credits.html',
        name: 'credits'
    },
    {
        path: '/settings',
        name: 'settings',
        async: function ( {resolve}) {
            var settings = [];
            settings.push(
                    {
                        setting: "display",
                        title: "Display and Appearance",
                        text: "",
                        onclick: "router.navigate('/settings/display')",
                        link: true
                    }
            );

            settings.push(
                    {
                        setting: "resetaccount",
                        title: "Forget Account",
                        text: "Log out and disconnect from your Helena Express account.",
                        onclick: "resetAccountPrompt()",
                        link: true
                    },
                    {
                        setting: "versions",
                        title: "Helena Express app v" + app_version,
                        text: "Copyright &copy; 2019-2021 Netsyms Technologies.",
                        onclick: ""
                    },
                    {
                        setting: "opensource",
                        title: "Credits and open source info",
                        text: "",
                        onclick: "router.navigate('/credits')",
                        link: true
                    },
                    {
                        setting: "privacy",
                        title: "Privacy policy and legal",
                        text: "",
                        onclick: "openBrowser('https://netsyms.com/legal?mtm_campaign=HelenaExpressApp')",
                        link: true
                    });
            resolve({
                content: compiledPages.settings({
                    page_title: "Settings",
                    settings: settings
                })
            });
        },
        routes: [
            {
                path: '/display',
                name: 'settings',
                async: function ({resolve}) {
                    var settings = [
                        {
                            setting: "apptheme",
                            title: "Color theme",
                            select: true,
                            options: [
                                {
                                    value: "auto",
                                    label: "Auto",
                                    selected: getStorage("apptheme") == null || getStorage("apptheme") == "auto"
                                },
                                {
                                    value: "dark",
                                    label: "Dark",
                                    selected: getStorage("apptheme") == "dark"
                                },
                                {
                                    value: "light",
                                    label: "Light",
                                    selected: getStorage("apptheme") == "light"
                                }
                            ]
                        },
                        {
                            setting: "animation",
                            title: "Animations",
                            select: true,
                            options: [
                                {
                                    value: "auto",
                                    label: "On",
                                    selected: getStorage("animation") == null || getStorage("animation") == "auto" || getStorage("animation") == "on"
                                },
//                                {
//                                    value: "on",
//                                    label: "On",
//                                    selected: getStorage("animation") == "on"
//                                },
                                {
                                    value: "off",
                                    label: "Off",
                                    selected: getStorage("animation") == "off"
                                }
                            ]
                        },
                        {
                            setting: "hideaccountnag",
                            title: "Hide \"Finish Account Setup\"",
                            text: "",
                            toggle: true,
                            checked: getStorage("hideaccountnag") == "true",
                            onclick: ""
                        }
                    ];
                    resolve({
                        content: compiledPages.settings({
                            page_title: "Display Settings",
                            settings: settings
                        })
                    });
                }
            }
        ]
    }
];
