/*
 * Copyright 2020 Netsyms Technologies.
 * 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/.
 */

var pdfobject = null;

function labelListAsync(routeTo, routeFrom, resolve, reject) {
    app.dialog.preloader("Loading...");
    apirequest(
            "listlabels",
            {},
            function (resp) {
                app.dialog.close();
                if (resp.status == "ERROR") {
                    app.dialog.alert(resp.msg, "Error");
                    reject();
                } else {
                    var context = {
                        labels: resp.labels,
                        machineid: routeTo.params.machineid
                    };
                    resolve({
                        templateUrl: "pages/labels.html",
                    }, {
                        context: context
                    });
                }
            },
            function (xhr) {
                app.dialog.close();
                var error = $.parseJSON(xhr.responseText);
                if (error && typeof error.msg != 'undefined') {
                    app.dialog.alert(error.msg, "Error");
                } else {
                    app.dialog.alert("A server or network error occurred.", "Error");
                }
                reject();
            });
}

function getPDFLabelAndDisplay(machineid, labeltype) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            //this.response is what you're looking for
            pdfobject = this.response;

            $("#print-fab").removeClass("display-none");
            $("#pdf-canvas").removeClass("display-none");
            $("#pdf-loading-message").addClass("display-none");

            pdfjsLib.getDocument({data: pdfobject}).promise.then(function (pdf) {
                pdf.getPage(1).then(function (page) {
                    var scale = 1.5;
                    var viewport = page.getViewport({scale: scale});

                    var canvas = document.getElementById('pdf-canvas');
                    var context = canvas.getContext('2d');
                    canvas.height = viewport.height;
                    canvas.width = viewport.width;

                    var renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };
                    page.render(renderContext);
                });
            });
        }
    }
    xhr.open('POST', SETTINGS.apiserver + "getlabel", true, getStorage("username"), getStorage("password"));
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.responseType = 'arraybuffer';
    xhr.send("id=" + machineid + "&type=" + labeltype);
}

function sendPDFToPrintServer() {
    var bytesArray = new Uint8Array(pdfobject);

    var printurl = getStorage("printserverurl");

    $.getJSON(printurl, {action: "list"}, function (resp) {
        var printers = resp.printers;

        var buttons = [];
        for (var i = 0; i < printers.length; i++) {
            buttons.push({
                text: printers[i]
            });
        }
        app.dialog.create({
            title: 'Print',
            text: 'Select a printer',
            buttons: buttons,
            verticalButtons: true,
            onClick: function (dialog, index) {
                var printer = printers[index];

                $.ajax({
                    url: printurl + '?action=print&printer=' + printer,
                    type: 'POST',
                    contentType: 'application/octet-stream',
                    data: bytesArray,
                    processData: false
                });
            }
        }).open();

    });
}