var alreadyStarted = false;

function SparepartBarcodeHandler() {

    var uo = null;
    var testSwitch = true;
    //var moveToInfoPageRequested = false;
    var sparePartInfoRequested = false;

    var resultCollector = Quagga.ResultCollector.create({
        capture: true,
        capacity: 20,
        blacklist: [{
            code: "WIWV8ETQZ1", format: "code_93"
        }, {
            code: "EH3C-%GU23RK3", format: "code_93"
        }, {
            code: "O308SIHQOXN5SA/PJ", format: "code_93"
        }, {
            code: "DG7Q$TV8JQ/EN", format: "code_93"
        }, {
            code: "VOFD1DB5A.1F6QU", format: "code_93"
        }, {
            code: "4SO64P4X8 U4YUU1T-", format: "code_93"
        }],
        filter: function (codeResult) {
            // only store results which match this constraint
            // e.g.: codeResult
            return true;
        }
    });

    var SparepartBarcodeReader = {

        //setUser: function (_uo)
        //{
        //    uo = _uo; 
        //},

        init: function () {
            

            var self = this;

            
            Quagga.init(this.state, function (err) {
                if (err) {
                    return self.handleError(err);
                }
                //Quagga.registerResultCollector(resultCollector);
                //MachineBarcodeReader.attachListeners();
                SparepartBarcodeReader.checkCapabilities();

                decoder: {
                        readers: ["code_128_reader"]
                }

                Quagga.start();
                alreadyStarted = true;


                //$('#cam_start').css('margin-top', $('video').offset().top + $('video').height());
                //$('#cam_stop').css('margin-top', $('video').offset().top + $('video').height());

            });
        },

        handleError: function (err) {
            console.log(err);
        },

        checkCapabilities: function () {
            var track = Quagga.CameraAccess.getActiveTrack();
            var capabilities = {};
            if (typeof track.getCapabilities === 'function') {
                capabilities = track.getCapabilities();
            }
            this.applySettingsVisibility('zoom', capabilities.zoom);
            this.applySettingsVisibility('torch', capabilities.torch);
        },

        updateOptionsForMediaRange: function (node, range) {
            console.log('updateOptionsForMediaRange', node, range);
            var NUM_STEPS = 6;
            var stepSize = (range.max - range.min) / NUM_STEPS;
            var option;
            var value;
            while (node.firstChild) {
                node.removeChild(node.firstChild);
            }
            for (var i = 0; i <= NUM_STEPS; i++) {
                value = range.min + (stepSize * i);
                option = document.createElement('option');
                option.value = value;
                option.innerHTML = value;
                node.appendChild(option);
            }
        },

        applySettingsVisibility: function (setting, capability) {
            // depending on type of capability
            if (typeof capability === 'boolean') {
                var node = document.querySelector('input[name="settings_' + setting + '"]');
                if (node) {
                    node.parentNode.style.display = capability ? 'block' : 'none';
                }
                return;
            }
            if (window.MediaSettingsRange && capability instanceof window.MediaSettingsRange) {
                var node = document.querySelector('select[name="settings_' + setting + '"]');
                if (node) {
                    this.updateOptionsForMediaRange(node, capability);
                    node.parentNode.style.display = 'block';
                }
                return;
            }
        },

        initCameraSelection: function () {

            var streamLabel = Quagga.CameraAccess.getActiveStreamLabel();

            return Quagga.CameraAccess.enumerateVideoDevices()
                .then(function (devices) {
                    //function pruneText(text) {
                    //    return text.length > 30 ? text.substr(0, 30) : text;
                    //}
                    //var $deviceSelection = document.getElementById("deviceSelection");
                    //while ($deviceSelection.firstChild) {
                    //    $deviceSelection.removeChild($deviceSelection.firstChild);
                    //}
                    //devices.forEach(function (device) {
                    //    var $option = document.createElement("option");
                    //    $option.value = device.deviceId || device.id;
                    //    $option.appendChild(document.createTextNode(pruneText(device.label || device.deviceId || device.id)));
                    //    $option.selected = streamLabel === device.label;
                    //    $deviceSelection.appendChild($option);
                    //});
                });
        },

        attachListeners: function () {
            var self = this;

            self.initCameraSelection();
            $(".controls").on("click", "button.stop", function (e) {
                e.preventDefault();
                Quagga.stop();
                self._printCollectedResults();
            });

            $("#cam_start").unbind().click(function () {
                $(".video").show();
                $(".drawingBuffer").show();
                $(".spac").show();
                //$("#cam_start").css('margin-top', '399px');
                //$("#cam_stop").css('margin-top', '399px');
                //$('#cam_start').css('margin-top', $('video').offset().top + $('video').height() - (70));
                //$('#cam_stop').css('margin-top', $('video').offset().top + $('video').height() - (70));

                SparepartBarcodeReader.init();

                document.getElementsByClassName('video')[0].play();
            });

            $("#cam_stop").unbind().click(function () {
                SparepartBarcodeReader.detachListeners();
                Quagga.stop();
                document.getElementsByClassName('video')[0].pause();
                document.getElementsByClassName('video')[0].currentTime = 0;

                $(".video").hide();
                $(".drawingBuffer").hide();

                //$('#cam_start').css('margin-top', 'inherit');
                //$('#cam_stop').css('margin-top', 'inherit');
            });

            $(".controls .reader-config-group").on("change", "input, select", function (e) {
                e.preventDefault();
                var $target = $(e.target),
                    value = $target.attr("type") === "checkbox" ? $target.prop("checked") : $target.val(),
                    name = $target.attr("name"),
                    state = self._convertNameToState(name);

                self.setState(state, value);
            });
        },

        ShutdownCamera : function () {
            SparepartBarcodeReader.detachListeners();
            Quagga.stop();
            //document.getElementsByClassName('video')[0].pause();
            //document.getElementsByClassName('video')[0].currentTime = 0;

            $(".video").hide();
            $(".drawingBuffer").hide();

            alreadyStarted = false;

        },

        StartCamera : function() {
            $(".video").show();
            $(".drawingBuffer").show();
            $(".spac").show();

            SparepartBarcodeReader.init();

            document.getElementsByClassName('video')[0].play();

        },

        _printCollectedResults: function () {
            //var results = resultCollector.getResults(),
            //    $ul = $("#result_strip ul.collector");

            //results.forEach(function (result) {
            //    var $li = $('<li><div class="thumbnail"><div class="imgWrapper"><img /></div><div class="caption"><h4 class="code"></h4></div></div></li>');

            //    $li.find("img").attr("src", result.frame);
            //    $li.find("h4.code").html(result.codeResult.code + " (" + result.codeResult.format + ")");
            //    $ul.prepend($li);
            //});
        },

        _accessByPath: function (obj, path, val) {
            var parts = path.split('.'),
                depth = parts.length,
                setter = (typeof val !== "undefined") ? true : false;

            return parts.reduce(function (o, key, i) {
                if (setter && (i + 1) === depth) {
                    if (typeof o[key] === "object" && typeof val === "object") {
                        Object.assign(o[key], val);
                    } else {
                        o[key] = val;
                    }
                }
                return key in o ? o[key] : {};
            }, obj);
        },

        _convertNameToState: function (name) {
            return name.replace("_", ".").split("-").reduce(function (result, value) {
                return result + value.charAt(0).toUpperCase() + value.substring(1);
            });
        },

        detachListeners: function () {
            $(".controls").off("click", "button.stop");
            $(".controls .reader-config-group").off("change", "input, select");
        },

        applySetting: function (setting, value) {
            var track = Quagga.CameraAccess.getActiveTrack();
            if (track && typeof track.getCapabilities === 'function') {
                switch (setting) {
                    case 'zoom':
                        return track.applyConstraints({ advanced: [{ zoom: parseFloat(value) }] });
                    case 'torch':
                        return track.applyConstraints({ advanced: [{ torch: !!value }] });
                }
            }
        },

        setState: function (path, value) {
            var self = this;

            if (typeof self._accessByPath(self.inputMapper, path) === "function") {
                value = self._accessByPath(self.inputMapper, path)(value);
            }

            if (path.startsWith('settings.')) {
                var setting = path.substring(9);
                return self.applySetting(setting, value);
            }
            self._accessByPath(self.state, path, value);

            //console.log(JSON.stringify(self.state));
            SparepartBarcodeReader.detachListeners();
            Quagga.stop();
            SparepartBarcodeReader.init();
        },

        inputMapper: {
            inputStream: {
                constraints: function (value) {
                    if (/^(\d+)x(\d+)$/.test(value)) {
                        var values = value.split('x');
                        return {
                            width: { min: parseInt(values[0]) },
                            height: { min: parseInt(values[1]) }
                        };
                    }
                    return {
                        deviceId: value
                    };
                }
            },

            numOfWorkers: function (value) {
                return parseInt(value);
            },

            decoder: {
                readers: function (value) {
                    if (value === 'ean_extended') {
                        return [{
                            format: "ean_reader",
                            config: {
                                supplements: [
                                    'ean_5_reader', 'ean_2_reader'
                                ]
                            }
                        }];
                    }
                    return [{
                        format: value + "_reader",
                        config: {}
                    }];
                }
            }
        },
        state: {
            inputStream: {
                type: "LiveStream",
                target: document.getElementById("sp_scan"), //$("fdgss")[0],
                constraints: {
                    width: { min: 200 },
                    height: { min: 200 },
                    facingMode: "environment",
                    aspectRatio: { min: 1, max: 2 }
                }
            },
            locator: {
                patchSize: "medium",
                halfSample: true
            },
            numOfWorkers: 1,
            frequency: 5,
            decoder: {
                readers: [
                {
                    format: "code_128_reader",
                    config: {}
                },
                 
                //{
                //    format: "code_39_reader",
                //    config: {}
                //},
                //{
                //    format: "ean_reader",
                //    config: {}
                //}
                ]
            },
            locate: true
        },
        lastResult: null,


        //PM5 Mobile section

        checkForSparepartExistenceOnBarcode : function () {
            var sparepart_search_param = this.lastResult;
            var current_session_token = $.cookie("session_token");
            var user_id = $.cookie("user_id");



            var requester = new AjaxRequest({
                data: { "sparepart_search_param": sparepart_search_param, "user_id": user_id, "session_token": current_session_token }, // This is for the json request
                success: function (data, status, xhr) {

                    var checkValidation = data.d.SessionTokenValid;
                    var sparepartsPresent = data.d.TrueOrFalse;
                    if (checkValidation == false) {

                        //$.mobile.navigate("#dialog_tokenexpired", { role: "dialog" });

                        $("#scansparepartwithcamera_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
                        $("#scansparepartwithcamera_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

                        $("#scansparepartwithcamera_generic_popup").off().on("popupafterclose", function (event, ui) {
                            $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                            e5('scansparepartwithcamera row 388');
                        });

                        $("scansparepartwithcamera_generic_popup_button").unbind("click").click(function () {
                            $("#scansparepartwithcamera_generic_popup").popup("close");
                        });

                        $("#scansparepartwithcamera_generic_popup").popup().popup("open");

                    }
                    else if (sparepartsPresent == false) {

                        $("#scansparepartwithcamera_errormessage_flash").text(ReturnPhraseOnKey("sp_barcodecam_scan_again_nosparepart_with_barcode") + ' ' + sparepart_search_param);
                        //$("#scansparepartwithcamera_errormessage").show().delay(3000).fadeOut(300);
                        SparepartBarcodeReader.lastResult = '';
                        SparepartBarcodeReader.sparePartInfoRequested = true;

                        Quagga.stop();

                        if ($("#scansparepartwithcamera_scanagain").is(":hidden")) {
                            $("#scansparepartwithcamera_scanagain").show();
                        }


                    }

                    else if (sparepartsPresent == true) {
                        //if ($("#scanwithcamera_errormessage").is(":visible")) {
                        //    $("#scanwithcamera_errormessage").hide();
                        //}

                        if (data.d.StringToPass !== undefined) {
                            $.cookie("currently_selected_sparepartid", data.d.StringToPass);
                        }

                        $.cookie("sparepartsearchparam", "");


                        $.cookie("sparepartsearchparam", sparepart_search_param);
                        $.cookie("spareparttypesearchparam", $("#sparepartsearch_sparepartgroups").val());

                        //Set barcode reading from text fields to nothing - otherwise scanning will continue after each enter button entry
                        initScanner(undefined);

                        if (SparepartBarcodeReader.sparePartInfoRequested == false) {
                            if (testSwitch == true) {
                                SparepartBarcodeReader.sparePartInfoRequested = true;
                            }
                            //$.mobile.navigate("#page_sparepartlist", { role: "page" });

                            if (currently_selected_application_section == SPAREPARTS_SECTION) {
                                
                                $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlistonstore", { role: "page", reverse: false, changeHash: false });
                                e5('scansparepartwithcamera row 441');
                            }
                            else {
                                $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlist", { role: "page", reverse: false, changeHash: false });
                                e5('scansparepartwithcamera row 445');
                            }
                        }
                    }

                },
                error: function (data, status, xhr) {
                    c1("scansparepartswithcamera row 450: Unable to reach web service. Can't verify presence of machine search result.");
                    DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
                },
                url: "CheckForSparepartPresenceOnBarcode"
            });
            requester.ExecuteRequest();
        },

        checkForSparepartExistenceOnBarcodeAndStore : function(){

            var sparepart_search_param = this.lastResult;
            var spareparttype_search_param = '0';
            var current_store_id = CURRENT_SELECTED_STORE;
            var current_session_token = $.cookie("session_token");


            var requester = new AjaxRequest({
                data: { "sparepart_search_param": sparepart_search_param, "spareparttype_search_param":spareparttype_search_param, "store_id": current_store_id, "session_token": current_session_token }, // This is for the json request
                success: function (data, status, xhr) {

                    var checkValidation = data.d.SessionTokenValid;
                    var stockCount = data.d.ValueToPass;

                    c_objects(data.d);


                    if (checkValidation == false) {


                        $("#scansparepartwithcamera_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
                        $("#scansparepartwithcamera_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

                        $("#scansparepartwithcamera_generic_popup").off().on("popupafterclose", function (event, ui) {
                            $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                            e5('scansparepartwithcamera row 486');
                        });

                        $("scansparepartwithcamera_generic_popup_button").unbind("click").click(function () {
                            $("#scansparepartwithcamera_generic_popup").popup("close");
                        });

                        $("#scansparepartwithcamera_generic_popup").popup().popup("open");
                    }
                    else {
                        var stockCount = data.d.ValueToPass;
                        var sparePartId = data.d.StringToPass;

                        if (stockCount == 0) {
                            $("#scansparepartwithcamera_errormessage_flash").text(ReturnPhraseOnKey("sparepartsearchinstore_message_nosparepartstocksfound_alt_B") + storeSelect.SelectedStoreName);
                            $("#info_sparepart_camBarcodeScanner").hide();

                            SparepartBarcodeReader.lastResult = '';
                            SparepartBarcodeReader.sparePartInfoRequested = true;

                            Quagga.stop();

                            if ($("#scansparepartwithcamera_scanagain").is(":hidden")) {
                                $("#scansparepartwithcamera_scanagain").show();
                            }

                        }
                        else {

                            $.cookie("sparepartsearchparam", sparepart_search_param);
                            $.cookie("spareparttypesearchparam", spareparttype_search_param);

                            if (SparepartBarcodeReader.sparePartInfoRequested == false) {
                                if (testSwitch == true) {
                                    SparepartBarcodeReader.sparePartInfoRequested = true;
                                }

                                $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlistonstore", { role: "page", reverse: false, changeHash: false });
                                e5('scansparepartwithcamera row 523');
                            }
                        }
                    }
                },


                error: function (data, status, xhr) {
                    c1('scansparepatrswithcamera row 527: Failed to get number of stocks for spare part at selected store. Unable to reach web service.');
                    DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
                },

                url: "CheckForSparepartPresenceAtSpecificStore"
            });
            requester.ExecuteRequest();
        },

        handleHeaderText: function () {
            if (currently_selected_application_section == SPAREPARTS_SECTION) {
                $("#scansparepartwithcamera_errormessage_flash").text(ReturnPhraseOnKey("sparepartsearchinstore_header") + storeSelect.SelectedStoreName);
            }
            else {
                $("#scansparepartwithcamera_errormessage_flash").text(ReturnPhraseOnKey("sp_barcodecam_info_text"));
            };
        }

        //requestSparePartList : function () {
        //    var sparepart_search_param = $.cookie("sparepartsearchparam");
        //    var sparepart_group_search_param = $.cookie("spareparttypesearchparam");
        //    var current_session_token = $.cookie("session_token");

        //    console.log(current_session_token);

        //    var requester = new AjaxRequest({
        //        data: { "partial_sp_number": sparepart_search_param, "sparepart_group_id": sparepart_group_search_param, "session_token": current_session_token },
        //        success: function (data, status, xhr) {

        //                if (data.d.SessionTokenValid == false) {
        //                    console.log("token not valid, moving to dialog");
        //                    $.mobile.navigate("#dialog_tokenexpired", { role: "dialog" });
        //                }
        //                else {

        //                    c3('trying to build list after getting data');
        //                    console.log(data.d);
        //                    var sp_object = data.d.SparePartList[0];
        //                    console.log(sp_object);

        //                    $.cookie("currently_selected_sparepartnumber", sp_object.SparePartNumber);
        //                    $.cookie("currently_selected_sparepartid", sp_object.SparePartId);

        //                    $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlist", { role: "page", reverse: false, changeHash: false });
        //                 }
        //        },
        //        error: function (data, status, xhr) {

        //            console.log('Failed to retrieve spare part search list. Unable to reach web service.');
        //            DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
        //        },
        //        url: "RequestSparePartListOnPartialNumber"
        //    });
        //    requester.ExecuteRequest();

        //}

    };

    SparepartBarcodeReader.init();


    Quagga.onProcessed(function (result) {
        var drawingCtx = Quagga.canvas.ctx.overlay,
            drawingCanvas = Quagga.canvas.dom.overlay;

        if (result) {
            //if (result.boxes) {
            //    drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
            //    result.boxes.filter(function (box) {
            //        return box !== result.box;
            //    }).forEach(function (box) {
            //        Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, { color: "pink", lineWidth: 2 });
            //    });
            //}

            //if (result.box) {
            //    Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, { color: "yellow", lineWidth: 2 });
            //}

            //if (result.codeResult && result.codeResult.code) {
            //    Quagga.ImageDebug.drawPath(result.line, { x: 'x', y: 'y' }, drawingCtx, { color: "olivedrab", lineWidth: 3 });
            //}
        }
    });

    Quagga.onDetected(function (result) {

        var currentPageId = $.mobile.activePage.attr("id")
        var code = result.codeResult.code;

        if (SparepartBarcodeReader.lastResult !== code)
        {
            
 
        if (code != null)

        {
            SparepartBarcodeReader.lastResult = code;
            var currentActivePage = $.mobile.activePage.attr("id");
            if (currentActivePage == "page_sparepart_barcode_cam") {
                if (currently_selected_application_section == SPAREPARTS_SECTION) {
                    SparepartBarcodeReader.checkForSparepartExistenceOnBarcodeAndStore();
                }
                else {
                    SparepartBarcodeReader.checkForSparepartExistenceOnBarcode();
                }
            }

        }
   
        }
    });


    return SparepartBarcodeReader;
}

var sparepartBarcodeHandler = null;

$(document).on("pagebeforeshow", "#page_sparepart_barcode_cam", function (e) {
    $("#scansparepartwithcamera_scanagain").hide();
    //$("#scansparepartwithcamera_errormessage_flash").text(ReturnPhraseOnKey("sp_barcodecam_info_text"));
    $("#scansparepartwithcamera_errormessage_flash").text('');
    $("#scansparepartwithcamera_errormessage_flash").show();
});


$(document).on("pageshow", "#page_sparepart_barcode_cam", function (e) {
    sparepartBarcodeHandler = SparepartBarcodeHandler();
    sparepartBarcodeHandler.sparePartInfoRequested = false;

    sparepartBarcodeHandler.handleHeaderText();

    CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_BARCODE;


    sparepartBarcodeHandler.init();

    if ($("#page_sparepart_barcode_cam.video").is(":hidden")) {
        $("#page_sparepart_barcode_cam.video").show();
    }
    if ($("#page_sparepart_barcode_cam.drawingBuffer").is(":hidden")) {
        $("#page_sparepart_barcode_cam.drawingBuffer").show();
    }

    if ($("#page_sparepart_barcode_cam.spac").is(":hidden")) {
        $("#page_sparepart_barcode_cam.spac").show();
    }

    if ($("#info_sparepart_camBarcodeScanner").is(":hidden")) {
        $("#info_sparepart_camBarcodeScanner").show();
    }


    //$("#scanwithcamera_sparepart_switchtomanualinput").unbind().click(function (event) {
    //    //$(":mobile-pagecontainer").pagecontainer("change", "#page_machineselect", { role: "page", reverse: false, changeHash: false });
    //    if (currently_selected_application_section == SPAREPARTS_SECTION) {
    //        $.mobile.navigate("#page_sparepartselectinstore", { role: "page" });
    //        e5('scansparepartwithcamera row 686');
    //    }
    //    else {
    //        $.mobile.navigate("#page_sparepartselect", { role: "page" });
    //        e5('scansparepartwithcamera row 690');
    //    }
    //});

    $("#sparepart_camera_switch_to_manual").unbind().click(function (event) {
        //$(":mobile-pagecontainer").pagecontainer("change", "#page_machineselect", { role: "page", reverse: false, changeHash: false });
        if (currently_selected_application_section == SPAREPARTS_SECTION) {
            $.mobile.navigate("#page_sparepartselectinstore", { role: "page" });
        }
        else {
            $.mobile.navigate("#page_sparepartselect", { role: "page" });
        }
    });



    $("#scansparepartwithcamera_scanagain").unbind().click(function (event) {
        event.preventDefault();
        sparepartBarcodeHandler.init();
        alreadyStarted = true;
        if ($("#info_sparepart_camBarcodeScanner").is(":hidden")) {
            $("#info_sparepart_camBarcodeScanner").show();
        }
        sparepartBarcodeHandler.sparePartInfoRequested = false;
        sparepartBarcodeHandler.handleHeaderText();
        //$("#scansparepartwithcamera_errormessage_flash").text(ReturnPhraseOnKey("sp_barcodecam_info_text"));

        $("#scansparepartwithcamera_scanagain").hide().fadeOut(1000);
    });
});

$(document).on("pagehide", "#page_sparepart_barcode_cam", function () {
    sparepartBarcodeHandler.ShutdownCamera();
    sparepartBarcodeHandler.lastResult = '';

});
