/*
 * 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 show_help = function () {
    return getStorage("show_help") != "false";
}

var routes = [
    {
        path: '/home',
        name: 'home',
        async: function (routeTo, routeFrom, resolve, reject) {
            var total = countPackages();
            var undelivered = countRemainingPackages();
            var delivered = total - undelivered;
            var percent = (total > 0 ? (delivered / total) : 1);
            resolve({
                templateUrl: './pages/home.html'
            }, {
                context: {
                    packageTotal: total,
                    packageLeft: undelivered,
                    packageDelivered: delivered,
                    packagePercent: percent,
                    oldui: inStorage("oldhomeui") && getStorage("oldhomeui") == "true",
                    pages: [
                        {
                            title: "Add Items",
                            href: "/add",
                            icon: "fas fa-truck-loading",
                            bg: "add.svg"
                        },
                        {
                            title: "Item List",
                            href: "/list",
                            icon: "fas fa-list",
                            bg: "list.svg"
                        },
                        {
                            title: "Delivery Map",
                            href: "/map",
                            icon: "fas fa-map",
                            bg: "map.svg"
                        },
                        {
                            title: "Route Notes",
                            href: "/myroute",
                            icon: "fas fa-sticky-note",
                            bg: "notes.svg"
                        },
                        {
                            title: "Toolbox",
                            href: "/toolbox",
                            icon: "fas fa-tools",
                            bg: "toolbox.svg"
                        },
                        {
                            title: "Settings",
                            href: "/settings",
                            icon: "fas fa-cog",
                            bg: "settings.svg"
                        }
                    ]
                }
            });
        }
    },
    {
        path: '/add',
        name: 'add',
        async: function (routeTo, routeFrom, resolve, reject) {
            let tablet = $(window).width() >= 768;
            resolve({
                templateUrl: './pages/add.html',
            }, {
                context: {
                    show_help: show_help,
                    itemtypes: SETTINGS.itemtypes,
                    nottablet: !tablet
                }
            })
        },
        on: {
            pageAfterIn: function () {
                setupStreetAutofill("#streetInput", "input[name=number]");
            }
        }
    },
    {
        path: '/list',
        name: 'list',
        templateUrl: './pages/list.html',
        options: {
            context: {
                show_help: show_help
            }
        },
        on: {
            pageAfterIn: function () {
                loadPackageList();
                searchbar = app.searchbar.create({
                    el: '.package-list-searchbar',
                    searchContainer: '#addresslist',
                    searchIn: '.item-title',
                    backdrop: false,
                    on: {
                        search(sb, query, previousQuery) {
                            console.log(query, previousQuery);
                        }
                    }
                });
            }
        }
    },
    {
        path: '/map',
        templateUrl: './pages/map.html',
        name: 'map',
        options: {
            context: {
                show_help: show_help
            }
        },
        on: {
            pageAfterIn: function () {
                reloadMap();
            }
        }
    },
    {
        path: '/myroute',
        name: 'myroute',
        async: function (routeTo, routeFrom, resolve, reject) {
            var notes = false;
            if (inStorage("notes")) {
                notes = JSON.parse(getStorage("notes"));
                if (notes.length == 0) {
                    notes = false;
                }
            }
            resolve({
                templateUrl: './pages/myroute.html'
            }, {
                context: {
                    notes: notes
                }
            });
        },
        on: {
            pageAfterIn: function () {
                notessearchbar = app.searchbar.create({
                    el: '.notes-list-searchbar',
                    searchContainer: '#noteslist',
                    searchIn: '.item-title',
                    backdrop: false,
                    on: {
                        search(sb, query, previousQuery) {
                            console.log(query, previousQuery);
                        }
                    }
                });
            }
        },
        routes: [
            {
                path: '/addnote',
                on: {
                    pageAfterIn: function () {
                        setupStreetAutofill("input[name=street]", "input[name=number]");
                    }
                },
                async: function (routeTo, routeFrom, resolve, reject) {
                    var uuid = uuidv4();
                    resolve({
                        templateUrl: './pages/myroute/editnote.html'
                    }, {
                        context: {
                            noteid: uuid,
                            title: "Add Note",
                            toggles: SETTINGS.routenotetoggles,
                            note: {
                                id: uuid,
                                number: "",
                                street: "",
                                zipcode: inStorage("zipcode") ? getStorage("zipcode") : "",
                                route: inStorage("lastrouteid") ? getStorage("lastrouteid") : "",
                                notes: "",
                                toggles: {}
                            }
                        }
                    });
                },
            },
            {
                path: '/editnote',
                templateUrl: './pages/myroute/editnote.html',
                on: {
                    pageAfterIn: function () {
                        setupStreetAutofill("input[name=street]", "input[name=number]");
                    }
                },
                options: {
                    context: {
                        title: "Edit Note",
                        toggles: SETTINGS.routenotetoggles
                    }
                }
            }
        ]
    },
    {
        path: '/login',
        templateUrl: './pages/login.html',
        name: 'login'
    },
    {
        path: '/toolbox',
        name: 'toolbox',
        async: function (routeTo, routeFrom, resolve, reject) {
            resolve({
                templateUrl: './pages/toolbox.html'
            }, {
                context: {
                    oldui: inStorage("oldhomeui") && getStorage("oldhomeui") == "true",
                    pages: [
                        {
                            title: "Broken Scanner",
                            href: "/toolbox/scanner",
                            icon: "fas fa-barcode",
                            bg: "toolbox_scanner.svg"
                        },
                        {
                            title: "Track Item",
                            href: "/toolbox/track",
                            icon: "fas fa-search",
                            bg: "toolbox_track.svg"
                        },
                        {
                            title: "Weather Lookahead",
                            href: "/toolbox/weather",
                            icon: "fas fa-cloud-sun",
                            bg: "toolbox_weather.svg"
                        },
                        {
                            title: "Address Lookup",
                            href: "/toolbox/addrlookup",
                            icon: "fas fa-search-location",
                            bg: "toolbox_addrlookup.svg"
                        },
                        {
                            title: "Activity Log",
                            href: "/toolbox/log",
                            icon: "fas fa-book",
                            bg: "toolbox_log.svg"
                        },
                        {
                            title: "Share Item List",
                            href: "/toolbox/sharelist",
                            icon: "fas fa-share-alt",
                            bg: "toolbox_sharelist.svg"
                        }
                    ]
                }
            });
        },
        routes: [
            {
                path: '/scanner',
                templateUrl: './pages/toolbox/scanner.html',
                routes: [
                    {
                        path: '/scanner',
                        templateUrl: './pages/toolbox/scanner/scanner.html',
                        name: 'scanner'
                    },
                    {
                        path: '/entries',
                        name: 'entries',
                        async: function (routeTo, routeFrom, resolve, reject) {
                            if (getStorage("scanevents") != null && getStorage("scanevents") != "[]") {
                                var entries = JSON.parse(getStorage("scanevents"));
                                for (i in entries) {
                                    entries[i].event = entries[i].event.join(' <i class="fas fa-chevron-right"></i> ');
                                }
                            } else {
                                var entries = false;
                            }

                            resolve({
                                templateUrl: './pages/toolbox/scanner/entries.html'
                            }, {
                                context: {
                                    entries: entries
                                }
                            });
                        },
                        on: {
                            pageAfterIn: function () {
                                $(".barcode_entry").each(function () {
                                    var code = $(this).data("barcode");
                                    JsBarcode("#barcode_" + code, code, {
                                        format: "code128",
                                        ean128: true,
                                        width: 2,
                                        height: 40
                                    });
                                });
                            }
                        }
                    }
                ]
            },
            {
                path: '/track',
                name: 'track',
                async: function (routeTo, routeFrom, resolve, reject) {
                    var history = getStorage("trackingcodehistory");
                    if (history == null) {
                        history = false;
                    } else {
                        history = JSON.parse(history).reverse(); // Most recent on top
                    }
                    resolve({
                        templateUrl: './pages/toolbox/track.html'
                    }, {
                        context: {
                            trackingcodehistory: history
                        }
                    });
                },
                routes: [
                    {
                        path: '/info',
                        templateUrl: './pages/toolbox/trackinginfo.html',
                        name: 'trackinginfo'
                    }
                ]
            },
            {
                path: '/weather',
                url: './pages/toolbox/weather.html',
                name: 'weather',
                on: {
                    pageAfterIn: function () {
                        loadWeather();
                    }
                }
            },
            {
                path: '/addrlookup',
                url: './pages/toolbox/addrlookup.html',
                name: 'addrlookup'
            },
            {
                path: '/log',
                name: 'log',
                async: function (routeTo, routeFrom, resolve, reject) {
                    var activitylog = getStorage("activitylog");
                    let events = [];
                    if (activitylog != null) {
                        try {
                            events = JSON.parse(activitylog);
                            events.sort(function (x, y) {
                                if (x.date < y.date) {
                                    return 1;
                                } else if (x.date > y.date) {
                                    return -1;
                                }
                                return 0;
                            });
                            let year = formatTimestamp("Y");
                            let yearmonth = formatTimestamp("Y-m");
                            let day = formatTimestamp("j");
                            for (var i = 0; i < events.length; i++) {
                                let evtdate = events[i].date;
                                if (formatTimestamp("Y-m", evtdate) == yearmonth) {
                                    // same year and month
                                    if (formatTimestamp("J", evtdate) - day < 7) {
                                        // same week
                                        events[i].date = formatTimestamp("l", evtdate);
                                        events[i].addldate = formatTimestamp("M j", evtdate);
                                    } else {
                                        events[i].date = formatTimestamp("D", evtdate);
                                        events[i].addldate = formatTimestamp("M j", evtdate);
                                    }
                                } else if (formatTimestamp("Y", evtdate) == year) {
                                    // same year
                                    events[i].date = formatTimestamp("M j", evtdate);
                                    events[i].addldate = year;
                                } else {
                                    // different year
                                    events[i].date = formatTimestamp("M j", evtdate);
                                    events[i].addldate = formatTimestamp("Y", evtdate);
                                }
                                events[i].entries.sort(function (x, y) {
                                    if (x.timestamp < y.timestamp) {
                                        return 1;
                                    } else if (x.timestamp > y.timestamp) {
                                        return -1;
                                    }
                                    return 0;
                                });
                                for (var j = 0; j < events[i].entries.length; j++) {
                                    events[i].entries[j].time = formatTimestamp("g:i a", events[i].entries[j].timestamp);
                                }
                            }
                            console.log(events);
                        } catch (ex) {
                            events = [];
                        }
                    }
                    console.log(events);
                    if (events == null || (typeof events == "object" && events.length == 0)) {
                        events = false;
                    }
                    resolve({
                        templateUrl: './pages/toolbox/log.html'
                    }, {
                        context: {
                            events: events
                        }
                    });
                }
            },
            {
                path: '/sharelist',
                url: './pages/toolbox/sharelist.html',
                name: 'sharelist'
            }
        ]
    },
    {
        path: '/help',
        routes: [
            {
                path: '/list',
                panel: {
                    url: './pages/help/list.html'
                }
            },
            {
                path: '/map',
                panel: {
                    url: './pages/help/map.html'
                }
            }
        ]
    },
    {
        path: '/credits',
        url: './pages/credits.html',
        name: 'credits'
    },
    {
        path: '/settings',
        name: 'settings',
        async: function (routeTo, routeFrom, resolve, reject) {
            var settings = [];
            if (getStorage("username") != null && getStorage("password") != null) {
                var lastsync = getStorage("lastsync");
                if (lastsync == null) {
                    lastsync = "never";
                } else {
                    lastsync = timestampToDateTimeString(lastsync);
                }
                settings.push(
                        {
                            setting: "account",
                            title: "Account",
                            text: "Logged in as " + getStorage("username") + "<br>" + "Last sync: " + lastsync
                        },
                        {
                            setting: "syncnow",
                            title: "",
                            text: "Sync now",
                            link: true,
                            onclick: "resyncAndRestart()"
                        },
                        {
                            setting: "logout",
                            title: "",
                            text: "Log out",
                            link: true,
                            onclick: "logout()"
                        }
                );
            } else {
                settings.push(
                        {
                            setting: "login",
                            title: "Account",
                            text: "Log in to backup and sync your settings and data.",
                            onclick: "router.navigate('/login')",
                            link: true
                        }
                );
            }
            settings.push(
                    {
                        setting: "alerts",
                        title: "Package Alerts",
                        text: "Change the alert sound, volume, and distance.",
                        onclick: "router.navigate('/settings/alerts')",
                        link: true
                    },
                    {
                        setting: "maps",
                        title: "Map and Navigation",
                        text: "Change map settings and units.",
                        onclick: "router.navigate('/settings/maps')",
                        link: true
                    },
                    {
                        setting: "display",
                        title: "Display and Appearance",
                        text: "Change the app theme, show/hide help bubbles, etc.",
                        onclick: "router.navigate('/settings/display')",
                        link: true
                    }
            );
            settings.push({
                setting: "hardwarescanner",
                title: "Use Hardware Scanner",
                text: "Enable scanning barcodes with a real scanner (not just a camera)",
                toggle: true,
                checked: getStorage("hardwarescanner") == "true",
                onclick: ""
            });
            // disable this because it's broken
            if (false && platform_type == "cordova" && cordova.platformId != "browser") {
                settings.push({
                    setting: "runinbackground",
                    title: "Run in background",
                    text: "Get package alerts when the screen is off or a different app is open.",
                    toggle: true,
                    checked: getStorage("runinbackground") == "true",
                    onclick: ""
                });
            }

            settings.push(
                    {
                        setting: "versions",
                        title: "PackageHelper app v" + app_version,
                        text: "Copyright &copy; 2019-2021 Netsyms Technologies.  Licensed under the Mozilla Public License 2.0.",
                        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?pk_campaign=PackageHelperApp')",
                        link: true
                    },
                    {
                        setting: "clearcache",
                        title: "Clear Cache",
                        text: "Delete saved maps and other temporary data",
                        link: true,
                        onclick: "clearCaches()"
                    });
            resolve({
                templateUrl: './pages/settings.html'
            }, {
                context: {
                    page_title: "Settings",
                    settings: settings
                }
            });
        },
        routes: [
            {
                path: '/alerts',
                name: 'settings',
                async: function (routeTo, routeFrom, resolve, reject) {
                    var alertsounds = [];
                    for (var id in SETTINGS.alertsounds) {
                        if (SETTINGS.alertsounds.hasOwnProperty(id)) {
                            alertsounds.push({
                                value: id,
                                label: SETTINGS.alertsounds[id].name,
                                selected: getStorage("alertsound") == id
                            });
                        }
                    }

                    var settings = [
                        {
                            setting: "alertsound",
                            title: "Alert sound",
                            text: "Select which sound to play when a package is nearby.",
                            select: true,
                            options: alertsounds
                        },
                        {
                            setting: "alertvolume",
                            title: "Alert volume",
                            min: 0,
                            max: 100,
                            step: 1,
                            value: getStorage("alertvolume"),
                            slider: true
                        },
                        {
                            setting: "alertradius",
                            title: "Alert radius (meters)",
                            min: 50,
                            max: 500,
                            step: 50,
                            value: getStorage("alertradius"),
                            slider: true
                        },
                        {
                            setting: "alertinterval",
                            title: "Alert interval (seconds)",
                            min: 15,
                            max: 120,
                            step: 15,
                            value: getStorage("alertinterval") == null ? 30 : getStorage("alertinterval"),
                            slider: true
                        }
                    ];
                    resolve({
                        templateUrl: './pages/settings.html'
                    }, {
                        context: {
                            page_title: "Alert Settings",
                            settings: settings
                        }
                    });
                }
            },
            {
                path: '/maps',
                name: 'settings',
                async: function (routeTo, routeFrom, resolve, reject) {
                    var mapstyles = [];
                    for (var id in SETTINGS.maptileurls) {
                        if (SETTINGS.maptileurls.hasOwnProperty(id)) {
                            mapstyles.push({
                                value: id,
                                label: SETTINGS.maptileurls[id].name,
                                selected: getStorage("mapsource") == id
                            });
                        }
                    }

                    var settings = [
                        {
                            setting: "mapsource",
                            title: "Map style",
                            select: true,
                            options: mapstyles,
                            text: "Choose which map style to use."
                        },
                        {
                            setting: "units",
                            title: "Measurement units",
                            select: true,
                            options: [
                                {
                                    value: "metric",
                                    label: "Meters/Kilometers",
                                    selected: getStorage("units") == "metric"
                                },
                                {
                                    value: "imperial",
                                    label: "Feet/Miles",
                                    selected: getStorage("units") == "imperial"
                                }
                            ]
                        },
                        {
                            setting: "trackzoom",
                            title: "Zoom when tracking location",
                            select: true,
                            options: [
                                {
                                    value: 15,
                                    label: "Low",
                                    selected: getStorage("trackzoom") == 15
                                },
                                {
                                    value: 16,
                                    label: "Normal",
                                    selected: getStorage("trackzoom") == null || getStorage("trackzoom") == 16
                                },
                                {
                                    value: 17,
                                    label: "High",
                                    selected: getStorage("trackzoom") == 17
                                }
                            ]
                        },
                        {
                            setting: "mapscale",
                            title: "Map Scale Ruler",
                            text: "Show a scale in the corner of the map.",
                            toggle: true,
                            checked: getStorage("mapscale") !== "false",
                            onclick: ""
                        },
                        {
                            setting: "maptype",
                            title: "Alternative map",
                            text: "Turn this on if you have problems with the map.",
                            toggle: true,
                            checked: getStorage("maptype") == "leaflet",
                            onclick: ""
                        }
                    ];
                    resolve({
                        templateUrl: './pages/settings.html'
                    }, {
                        context: {
                            page_title: "Map Settings",
                            settings: settings
                        }
                    });
                }
            },
            {
                path: '/display',
                name: 'settings',
                async: function (routeTo, routeFrom, resolve, reject) {
                    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"
                                },
                                {
                                    value: "oleddark",
                                    label: "Dark with anti-burn-in",
                                    selected: getStorage("apptheme") == "oleddark"
                                },
                            ]
                        },
                        {
                            setting: "liststyle",
                            title: "List Style",
                            select: true,
                            options: [
                                {
                                    value: "accordion",
                                    label: "Accordion",
                                    selected: getStorage("liststyle") == null || getStorage("liststyle") == "accordion"
                                },
                                {
                                    value: "swipe",
                                    label: "Swipe",
                                    selected: getStorage("liststyle") == "swipe"
                                }
                            ]
                        },
                        {
                            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"
                                }
                            ]
                        }
                    ];
                    if (platform_type == "cordova" && cordova.platformId != "browser" && typeof window.powerManagement != "undefined") {
                        settings.push({
                            setting: "wakelock",
                            title: "Keep screen on",
                            text: "",
                            toggle: true,
                            checked: getStorage("wakelock") == "true",
                            onclick: ""
                        });
                    }
                    settings.push({
                            setting: "showhelp",
                            title: "Show help",
                            text: "Show the <span class=material-icons-intext><i class=material-icons>help</i></span> icons",
                            toggle: true,
                            checked: getStorage("show_help") != "false",
                            onclick: ""
                        },
                        {
                            setting: "oldhomeui",
                            title: "Show home screen as list",
                            text: "Use a vertical list instead of tiles.",
                            toggle: true,
                            checked: getStorage("oldhomeui") == "true",
                            onclick: ""
                        }
                    );
                    resolve({
                        templateUrl: './pages/settings.html'
                    }, {
                        context: {
                            page_title: "Display Settings",
                            settings: settings
                        }
                    });
                }
            }
        ]
    }
];
