/*
 * 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, {
        phone: getStorage("phonenumber"),
        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!");
        } else if (resp.status == "ERROR") {
            app.dialog.alert(resp.msg, "Error");
        }
    }, function (error) {
        app.dialog.close();
        app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
    });
}
$("#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) {
    }, "");
});
$("#app").on("popup:open", "#dasLocationMapPopup", function () {
    if (mapboxgl.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 = " Unknown package size limits";
                            switch (type) {
                                case "micro":
                                    typedesc = " Fits envelopes";
                                    break;
                                case "mini":
                                    typedesc = " Fits large envelopes and small packages";
                                    break;
                                case "standard":
                                    typedesc = " Fits up to medium-size packages";
                                    break;
                                case "large":
                                    typedesc = " Fits most packages";
                                    break;
                                case "business":
                                    typedesc = " Shipping location, accepts any size package";
                                    break;
                            }
                            while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                                coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
                            }
                            new mapboxgl.Popup()
                                    .setLngLat(coordinates)
                                    .setHTML("" + name + "
" + typedesc
                                            + "
Hours:
" + hours
                                            + "
More Info:
" + info
                                            + "
 Directions")
                                    .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 {
        // Fall back to something
    }
});
$("#app").on("popup:open", "#dasHowItWorksPopup", function () {
    // Put user's account number in the instructions
    if (inStorage("phonenumber") && inStorage("accountkey")) {
        $("#dasHowItWorksAccountNumber").text(" (yours is " + getStorage("phonenumber") + ")");
    }
});