$(function() {
    var socket = io();
    var scripts = [
        "serialPortModuleFix",
        "softwarePkgSwitch",
        "addToDatabase",
        "removeFromDatabase",
        "upgradeDatabase",
        "addToPeripheralsFile",
        "addToEnvFile",
        "deleteData",
        "registerBusinessPremise"
    ];
    var documentscanner;
    setTimeout(function () {
        $.post("/api/peripherals/status", {});
        $.get("/api/device").then(function (posInfo) {
            $('#deviceinfo_c').html(posInfo.projectName);
            $('#deviceinfo_ca').html(posInfo.distributionVersionDownloaded);
            $('#deviceinfo_did').html(posInfo.deviceId);
            $('#deviceinfo_tid').html(posInfo.terminalId);
            $('#deviceinfo_d').html(posInfo.distributionVersion);
            $('#deviceinfo_a').html(posInfo.appVersion);

            $('#scripts-software').val(posInfo.appVersion);
        });
    }, 500);

    //////////////// Peripherals status ////////////////
    $('#redactor-drawer-box').addClass('hidden');
    socket.on('peripherals connected', function (peripherals) {
        for (var i=0; i<peripherals.length; i++) {
            if (peripherals[i].using) {
                $('#'+peripherals[i].device+'_status').removeClass('btn-default disabled').addClass('btn-danger');
                if (peripherals[i].device == 'cardprinter') {
                    $('#redactor-drawer-box').removeClass('hidden');
                }
            }
            if (peripherals[i].device == 'documentscanner') {
                documentscanner = peripherals[i].devicename;
            }
            if (peripherals[i].status == 'connected') {
                $('#'+peripherals[i].device+'_status').removeClass('disabled').removeClass('btn-danger').addClass('btn-success').attr('title', peripherals[i].device+' '+peripherals[i].status+' '+peripherals[i].changetimestamp.replace('T', ' ').slice(0, -5));
            } else {
                if (peripherals[i].using) {
                    $('#'+peripherals[i].device+'_status').removeClass('disabled').removeClass('btn-success').addClass('btn-danger').attr('title', peripherals[i].device+' '+peripherals[i].status+' '+peripherals[i].changetimestamp.replace('T', ' ').slice(0, -5));
                }
            }
        }
    });

    //////////////// Camera ////////////////
    var strem = document.querySelector('#camera');
    var screenshot = document.querySelector('#camera-pic');
    var video = document.querySelector('#camera-vid');
    var image = document.querySelector('#camera-img');
    strem.onclick = function () {
        navigator.mediaDevices.getUserMedia({video: true})
        .then(function (stream) { video.srcObject = stream; })
        .catch(function (error) { console.error('Error: ', error); });
    };
    screenshot.onclick = function () {
        var canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0);
        image.src = canvas.toDataURL('image/png'); // other browsers will fall back to image/png
        video.srcObject = null;
    };

    //////////////// Card reader ////////////////
    $('#cardreader-initialize').on('click', function (e) {
        if (!$(this).hasClass('disabled')) {
            $('#spiner-initialize').toggleClass('d-none');
            $.post("/api/ticket/initializeSmartCard", {uid: $('#card-uid').val(), content: JSON.parse($('#card-content').text())}).then(function (initialized) {
                $('#cardreader-initialize').removeClass('btn-primary').addClass('btn-success');
                $('#spiner-initialize').toggleClass('d-none');
            });
        }
    });
    socket.on('card connected', function (card) {
        $('#cardreader-initialize').removeClass('disabled');
        $('#card-uid').val(card.uid);
        $('#card-printed').val(getLuhnValidId(parseDecString(card.uid.match(/[a-fA-F0-9]{2}/g).reverse().join('')).toString().padStart(15, '0').slice(-15)));
        $('#card-connected').html('Card connected').removeClass('btn-primary').addClass((Object.keys(card.msg).length)?'btn-success':'btn-danger');
        $('#card-content').html('<pre><code>'+JSON.stringify(card.msg, null, 4)+'</code></pre>');

    });
    socket.on('card removed', function (card) {
        $('#cardreader-initialize').removeClass('btn-success').addClass('btn-primary disabled');
        $('#card-uid').val('');
        $('#card-printed').val('');
        $('#card-connected').html('No card').removeClass('btn-success btn-danger').addClass('btn-primary');
        $('#card-content').html('');
    });
    // SmartCardServ getLuhnValidId
    function getLuhnValidId(cardNumber) {
        if (/[^0-9-\s]+/.test(cardNumber)) { return false; }
        let sum = 0;
        let isDoubled = true;
        for (let i = cardNumber.length - 1; i >= 0; i--) {
            let digit = parseInt(cardNumber.charAt(i), 10);
            if (isDoubled) { if ((digit *= 2) > 9) { digit -= 9; } }
            sum += digit;
            isDoubled = !isDoubled;
        }
        return cardNumber.concat((sum * 9) % 10).toString();
    }
    // SmartCardServ parseDecString
    function parseDecString(str) {
        function add(x, y) {
            var c = 0, r = [];
            var x = x.split('').map(Number);
            var y = y.split('').map(Number);
            while (x.length || y.length) {
                var s = (x.pop() || 0) + (y.pop() || 0) + c;
                r.unshift(s < 10 ? s : s - 10);
                c = s < 10 ? 0 : 1;
            }
            if (c) r.unshift(c);
            return r.join('');
        }
        var dec = '0';
        str.split('').forEach(function(chr) {
            var n = parseInt(chr, 16);
            for (var t = 8; t; t >>= 1) {
                dec = add(dec, dec);
                if (n & t) dec = add(dec, '1');
            }
        });
        return dec;
    }

    //////////////// Receipt printer ////////////////
    $('#print').on('click', function (e) {
        if (!$('#print-file').val()) {
            $('#print-file').val('printdata');
        }
        $.get("assets/"+$('#print-file').val()+".json").then(function (printdata) {
            $.post("/api/peripherals/print", {text: printdata.text, qrcode: printdata.qrcode, text2: printdata.text2, qrcode2: printdata.qrcode2, text3: printdata.text3});
        });
    });

    //////////////// Cashdrawer ////////////////
    $('#cashdrawer').on('click', function (e) {
        $.post("/api/peripherals/openCashdrawer", {});
    });

    //////////////// Receipt printer paper status ////////////////
    $('#paper').on('click', function (e) {
        $.post("/api/peripherals/paper", {});
    });

    //////////////// Code scanner ////////////////
    $('#codescanner_status').on('click', function (e) {
        e.preventDefault();
        setTimeout(function () {
            $('#code-scanner').focus();
        }, 500);
    });

    //////////////// Document scanner ////////////////
    $('#scan').on('click', function (e) {
        $('#spiner-scan').toggleClass('d-none');
        $.post("/api/peripherals/scan", {scanner: documentscanner}).then(function (scanned) {
            $('#scanned-image').html('<img class="scanned" style="width: 100%" src="' + scanned.scan + '">');
            $('#spiner-scan').toggleClass('d-none');
        });
    });

    //////////////// Card printer ////////////////
    $('#drawerjs-canvas, #redactor-drawer-box').addClass('d-none');
    $('#drawerjs-canvas-action.dropdown-menu a').on('click', function (e) {
        switch ($(this).text()) {
            case 'Save':
                $.post("/api/peripherals/saveCardTemplate", {template: drawer.api.getCanvasAsJSON()});
            break;
            case 'Load':
                onStartEditing();
                $.post("/api/peripherals/loadCardTemplate", {template: ''}).then(function (canvas) { drawer.api.loadCanvasFromData({objects: [], background: ''}); drawer.api.loadCanvasFromData(canvas); });
                $('#drawerjs-canvas, #redactor-drawer-box').removeClass('d-none');
            break;
        }
    });
    $('#drawerjs-canvas-clear').on('click', function (e) {
        onStopEditing();
        $('#drawerjs-canvas, #redactor-drawer-box').addClass('d-none');
    });
    $('#drawerjs-image-preview').on('click', function (e) {
        $.post("/api/peripherals/previewCard", {value: $('#account-search').val()}).then(function (image) {
            var card = new Image(1014, 639);
            card.src = 'data:image/png;base64,' + image.previewCard;
            drawer.api.loadCanvasFromData({objects: [], background: ''});
            drawer.api.addImage(card, {centerImage: true});
            drawer.api.stopEditing();
            drawer.api.startEditing();
            $('#drawerjs-image-print').attr('data-accountId', image.previewId);
        });
        $('#drawerjs-canvas, #redactor-drawer-box').removeClass('d-none');
    });
    $('#drawerjs-image-print').on('click', function (e) {
        $.post("/api/peripherals/printCard", {value: $('#drawerjs-image-print').attr('data-accountId')}).then(function (image) {
            var card = new Image(1014, 639);
            card.src = 'data:image/png;base64,' + image.printCard;
            drawer.api.addImage(card, {centerImage: true});
            drawer.api.stopEditing();
            drawer.api.startEditing();
        });
        $('#drawerjs-canvas, #redactor-drawer-box').removeClass('d-none');
    });

    //////////////// Customer display ////////////////
    $('#display').on('click', function (e) {
        $.post("/api/peripherals/display", {text: "Amount to pay/return"+"9,999.99 EUR"});
    });

    //////////////// EDC terminal ////////////////
    $('#edcterminal').on('click', function (e) {
        $.post("/api/peripherals/edcTerminal", {transaction_type: 'C902'});
    });

    //////////////// Luggageprinter printer ////////////////
    $('#luggageprinter').on('click', function (e) {
        if (!$('#print-luggage-file').val()) {
            $('#print-luggage-file').val('printluggage');
        }
        $.get("assets/"+$('#print-luggage-file').val()+".json").then(function (printdata) {
            $.post("/api/peripherals/printluggage", {text: printdata.text, qrcode: printdata.qrcode});
        });
    });

    //////////////// Device status ////////////////
    $('#blockDevice').on('click', function (e) {
        $.post("/api/peripherals/block", {status: 'Block'});
    });
    $('#unblockDevice').on('click', function (e) {
        $.post("/api/peripherals/block", {status: 'Unblock'});
    });

    //////////////// Scripts ////////////////
    $('#scripts-dropdown').on('click', function (e) {
        $('#scripts-menu').toggle();
    });
    var form = '';
    var script = {};
    for (var i=0; i<scripts.length; i++) {
        form += '<div class="form-check py-2">';
        form +=     '<input type="checkbox" class="form-check-input" id="'+scripts[i]+'" value="'+scripts[i]+'">';
        form +=     '<label class="form-check-label" for="'+scripts[i]+'">'+scripts[i]+'</label>';
        form += '</div>';
        script[scripts[i]] = false;
    }
    $('#scripts-menu').prepend(form);
    $('#scripts-run').on('click', function (e) {
        script['softwareVersion'] = $("#scripts-software").val();
        var checks = $("#scripts-menu input[type='checkbox']:checked");
        for (var i=0; i<checks.length; i++) {
            script[$(checks[i]).val()] = true;
        }
        if (checks.length > 0) {
            $.post("/api/peripherals/scripts", script);
        }
        $('#scripts-menu').toggle();
    });

    //////////////// Penalty ////////////////
    $('#penalty-qr').on('click', function (e) {
        $.post("/api/peripherals/print", {text: '', qrcode: $('#penalty-ref').val(), text2: '', qrcode2: '', text3: ''});
    });

    $('#penalty-issue').on('click', function (e) {
        $.post("/api/penalty/issue", {short: $('#penalty').val()});
    });

});
