/*
 * 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 captureAndSendPickupCode() {
    scanBarcode(function (result) {
        var code = "";
        var coderegex = /^[0-9a-zA-Z]{5,40}$/;
        if (result.startsWith("https://helena.express/dropandsend#")) {
            code = result.split("#")[1];
        } else if (result.startsWith("https://helena.express/das/pickup#")) {
            code = result.split("#")[1];
        } else if (coderegex.test(result)) {
            code = result;
        } else {
            app.dialog.alert("That's not a valid Drop and Send pickup code.", "Error");
            return;
        }
        sendPickupCode(code);
    }, function () {
        app.dialog.prompt("Something went wrong while trying to scan the barcode. Type the location number to request a pickup.", "Send Pickup Code", function (code) {
            if (code == "") {
                app.dialog.alert("You didn't enter a location number.", "Error");
            } else {
                sendPickupCode(code);
            }
        }, function (cancel) {

        }, "");
    });
}

function sendPickupCode(code) {
    app.dialog.preloader("Loading...");
    apirequest(SETTINGS.apis.dropandsendpickup, {
        accountnumber: getStorage("accountnumber"),
        accountkey: getStorage("accountkey"),
        locationnumber: code
    }, function (resp) {
        app.dialog.close();
        if (resp.status == "OK") {
            app.dialog.alert("Thank you for using Helena Express! You'll get an emailed receipt after we pick up and process your package(s).", "Pickup Requested!");
            sendActionReport("Pickup", "Drop and Send", "Pickup requested");
        } else if (resp.status == "ERROR") {
            app.dialog.alert(resp.msg, "Error");
            sendErrorReport("Pickup", "Drop and Send", resp.msg);
        }
    }, function (xhr, status, error) {
        app.dialog.close();
        app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
        sendErrorReport("Pickup", "Drop and Send", "Server/network problem: " + xhr.status + ": " + xhr.statusText);
    });
}

$("#app").on("click", "#pickupCodeQRScanBtn", function () {
    captureAndSendPickupCode();
});

$("#app").on("click", "#pickupCodeManualEntryBtn", function () {
    app.dialog.prompt("Enter the location number to request a pickup.", "Send Pickup Code", function (code) {
        if (code == "") {
            app.dialog.alert("You didn't enter a location number.", "Error");
        } else {
            sendPickupCode(code);
        }
    }, function (cancel) {

    }, "");
});

$("body").on("popup:open", "#dasLocationMapPopup", function () {
    if (MapControl.supported()) {
        if (dropboxMap == null) {
            var mapboxel = document.getElementById("mapbox-dropboxes");
            dropboxMap = new MapControl(mapboxel, true);
            dropboxMap.reloadMap();
            dropboxMap.mapObj.on('load', function () {
                dropboxMap.mapObj.jumpTo({center: [-112.005, 46.589], zoom: 8});
                dropboxMap.loadIcon("./assets/images/dropbox-icon.png", "dropbox", function () {
                    apirequest(SETTINGS.apis.dropandsendlocations, {}, function (data) {
                        dropboxMap.loadMarkersFromGeoJson(data, "dropbox", "dropbox");
                        dropboxMap.mapObj.on('click', 'marker-layer-dropbox', function (e) {
                            var coordinates = e.features[0].geometry.coordinates.slice();
                            var name = e.features[0].properties.name;
                            var type = e.features[0].properties.type;
                            var info = e.features[0].properties.info;
                            var hours = e.features[0].properties.hours;
                            var geolink = "geo:" + (Math.round(coordinates[1] * 1000000) / 1000000) + "," + (Math.round(coordinates[0] * 1000000) / 1000000);

                            var typedesc = "";
                            switch (type) {
                                case "micro":
                                    typedesc = "<i class='fas fa-envelope'></i> Fits envelopes";
                                    break;
                                case "mini":
                                    typedesc = "<i class='fas fa-mail-bulk'></i> Fits large envelopes and small packages";
                                    break;
                                case "standard":
                                    typedesc = "<i class='fas fa-box-alt'></i> Fits up to medium-size packages";
                                    break;
                                case "large":
                                    typedesc = "<i class='fas fa-boxes-alt'></i> Fits most packages";
                                    break;
                                case "business":
                                    typedesc = "<i class='fas fa-store-alt'></i> Accepts all size packages";
                                    break;
                            }

                            while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                                coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
                            }

                            new maplibregl.Popup()
                                    .setLngLat(coordinates)
                                    .setHTML("<b>" + name + "</b><br>" + typedesc
                                            + "<br><b>Hours:</b><br>" + hours
                                            + "<br><b>More Info:</b><br>" + info
                                            + "<br><a class=\"button button-fill button-small\" href=\"" + geolink + "\"><i class=\"fas fa-location-circle\"></i> Directions</a>")
                                    .addTo(dropboxMap.mapObj);
                        });

                        dropboxMap.mapObj.on('mouseenter', 'marker-layer-dropbox', function () {
                            dropboxMap.mapObj.getCanvas().style.cursor = 'pointer';
                        });

                        dropboxMap.mapObj.on('mouseleave', 'marker-layer-dropbox', function () {
                            dropboxMap.mapObj.getCanvas().style.cursor = '';
                        });
                        dropboxMap.animateMapIn(46.589, -112.005, 9, 0);
                    }, function (error) {

                    }, "GET");
                });
            });
        }
    } else {
        showWebGLErrorMessage();
    }

    trackPageView("/dropandsend/locations_popup", $("#dasLocationMapPopup .navbar .navbar-inner .title").first().text());
});

$("body").on("popup:open", "#dasHowItWorksPopup", function () {
    // Put user's account number in the instructions
    if (inStorage("accountnumber") && inStorage("accountkey")) {
        $("#dasHowItWorksAccountNumber").text(" (yours is " + getStorage("accountnumber") + ")");
    }

    trackPageView("/dropandsend/howitworks_popup", $("#dasHowItWorksPopup .navbar .navbar-inner .title").first().text());
});