/*
 * 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 setupHardwareScanner() {
    try {
        onScan.detachFrom(document);
    } catch (ex) {
        // do nothing
    }

    if (getStorage("hardwarescanner") == "true") {
        onScan.attachTo(document, {
            suffixKeyCodes: [13], // enter-key expected at the end of a scan
            reactToKeyDown: true,
            reactToPaste: true, // Compatibility to built-in scanners in paste-mode (as opposed to keyboard-mode)
            ignoreIfFocusOn: 'input',
            stopPropagation: true,
            preventDefault: true,
            keyCodeMapper: function (evt) {
                // Handle special char codes
                switch (evt.which) {
                    case 119: // F8, separates 42012345 from actual tracking barcode
                        return "";
                }

                var char = String.fromCharCode(evt.which);
                // Handle special characters
                switch (char) {
                    case "\u0010": // In some fields in UPS MI codes but pointless
                        return "";
                }
                // Return everything that gets through the special cases above
                return char;
            },
            onScan: function (code, qty) { // Alternative to document.addEventListener('scan')
                console.log("Scanned: ", code);
                switch (router.currentRoute.name) {
                    case "add":
                        addPackageBarcode(code);
                        break;
                    case "track":
                        openTrackingHistory(code);
                        break;
                    case "scanner":
                        addCodeToScannerList(code);
                        break;
                }
            }
        });
    }
}

setupHardwareScanner();