//var url = "http://172.16.198.221:3000/api/";
var url = "https://salix.verdnatura.es/api/";
var urlweb = "https://verdnatura.es/";
var idArticulo = "";
var minCroppedWidth = 320;
var minCroppedHeight = 160;
var maxCroppedWidth = 4032;
var maxCroppedHeight = 2688;
var ratio = 1;
var maxAspectRatio = 1.5;
var image;

var cropper;



$(document).ready(function () {


    FastClick.attach(document.body);
    //setTimeout(scanBarcode, 1000);
    image = document.querySelector('#photo');
    maxCroppedWidth = image.naturalWidth;
    maxCroppedHeight = (maxCroppedWidth / 3) * 2;
    minCroppedWidth = maxCroppedWidth / 3;
    minCroppedHeight = maxCroppedHeight / 3;

    $("#btn1").on("click", function () {
        ratio = 1;
        $(".menubtn").children().removeClass("selected");
        $(this).addClass("selected");
        maxCroppedWidth = image.naturalWidth;
        maxCroppedHeight = (maxCroppedWidth / 3) * 2;

    });
    $("#btn2").on("click", function () {
        ratio = 2;
        $(".menubtn").children().removeClass("selected");
        $(this).addClass("selected");
        maxCroppedWidth = image.naturalWidth;
        maxCroppedHeight = (maxCroppedWidth / 16) * 9;


    });
    $("#btn3").on("click", function () {
        ratio = 3;
        $(".menubtn").children().removeClass("selected");
        $(this).addClass("selected");
        maxCroppedWidth = image.naturalWidth;
        maxCroppedHeight = (maxCroppedWidth / 1) * 1;

    });

    $(".btnback").on("click", function () {
        window.location = "main.html";
    });

    $(".btnsave").on("click", savePhoto);


    $(".btnbarcode").on("click", function () {
        $(".loading").fadeIn(200);
        scanBarcode();
    });
    $("#btntakepicture").on("click", setManualMode);

    $(".btnlogout").on("click", function () {
        localStorage.removeItem("user");
        localStorage.removeItem("password");
        window.location = "index.html";
    });

    $(".btnsalix").on("click", function () {
        var target = "_system";
        var options = "location=no";
        var url = "https://salix.verdnatura.es";
        var ref = cordova.InAppBrowser.open(url, target, options);
    });

    $("#txtarticle").on("keypress", function (event) {
        if (event.keyCode === 13) {
            setManualMode();
            event.preventDefault();
        }
    });

});

function setManualMode() {
    idArticulo = $("#txtarticle").val();

    if (idArticulo.trim().length > 0) {
        navigator.notification.confirm(
            'Article: ' + idArticulo, // message
            onConfirm, // callback to invoke with index of button pressed
            'Verdnatura says:', // title
            ['Hacer foto', 'Biblioteca', 'Cerrar']     // buttonLabels
        );
    } else {
        navigator.notification.alert("Insert manual id or scan article", null, "Verdnatura says:", "¡ups!");
    }

}
function savePhoto() {

    navigator.notification.confirm(
        'Estas seguro de actualizar la foto de: ' + idArticulo, // message
        confirmSave, // callback to invoke with index of button pressed
        'Verdnatura says:', // title
        ['Guardar', 'Cancelar']     // buttonLabels
    );

    //     confirmSave(1);

}
function confirmSave(buttonIndex) {
    if (buttonIndex == 1) {
        $(".loading").fadeIn(200);
        var img = dataURItoBlob(cropper.getCroppedCanvas().toDataURL('image/png'));

        var data = new FormData();
        data.append('srv', 'json:image/upload');
        data.append('schema', 'catalog');
        data.append('name', idArticulo);
        data.append('updateMatching', true);
        data.append('image', img);

        navigator.notification.alert("Error al cargar la foto", localStorage.getItem("user") + localStorage.getItem("password") + localStorage.getItem("token"));

        const xhr = new XMLHttpRequest();
        xhr.setRequestHeader('Authorization', localStorage.getItem('token'));
        xhr.open("POST", urlweb, true);
        xhr.send(data);
        xhr.onload = function () {
            var response = JSON.parse(xhr.response);
            if (!response.data == true) {
                navigator.notification.alert("Carga completa!", function () {
                    window.location = "main.html";
                }, "Verdnatura dice:", "¡Buen trabajo!");
            } else {
                navigator.notification.alert("Error al cargar la foto", null, "Verdnatura dice:", "¡ooohh!");
                $(".loading").fadeOut(500);
            }
        };
        xhr.onerror = function () {
            navigator.notification.alert("Error al cargar la foto", null, "Verdnatura dice:", "¡ooohh!");
            $(".loading").fadeOut(500);
        };
    }
}
function dataURItoBlob(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], { type: 'image/png' });
}
function scanBarcode() {

    cordova.plugins.barcodeScanner.scan(
        function (result) {
            idArticulo = result.text;

            navigator.notification.confirm(
                'Article: ' + result.text, // message
                onConfirm, // callback to invoke with index of button pressed
                'Verdnatura says:', // title
                ['Hacer foto', 'Bibloteca', 'Cerrar']     // buttonLabels
            );

        },
        function (error) {
            navigator.notification.alert(
                "Could not scan: " + error, // message
                onError, // callback
                'Game Over', // title
                'Ok'                  // buttonName
            );


        }
    );
}
function onConfirm(buttonIndex) {
    $(".menu").fadeOut(200);
    switch (buttonIndex) {
        case 1:
            showCamera();
            break;
        case 2:
            showLibrary();
            break;
        case 3:
            window.location = "main.html";
            break;
        default:
            window.location = "main.html";
    }
}
function onError() {
    window.location = "main.html";
}
function showCamera() {
    var srcType = Camera.PictureSourceType.CAMERA;

    var options = {
        saveToPhotoAlbum: true,
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: srcType,
        encodingType: Camera.EncodingType.JPEG,
        mediaType: Camera.MediaType.PICTURE,
        allowEdit: false,
        correctOrientation: true
    };



    navigator.camera.getPicture(cameraSuccess, cameraError, options);

}
function showLibrary() {
    var srcType = Camera.PictureSourceType.PHOTOLIBRARY;

    var options = {
        saveToPhotoAlbum: false,
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: srcType,
        encodingType: Camera.EncodingType.JPEG,
        mediaType: Camera.MediaType.PICTURE,
        allowEdit: false,
        correctOrientation: true
    };
    navigator.camera.getPicture(cameraSuccess, cameraError, options);

}
function cameraSuccess(imageData) {
    $(".loading").fadeOut(200);
    console.log("Camera success.");
    $("#photo").attr("src", imageData);


    setCrop();
}
function setCrop() {

    cropper = new Cropper(image, {
        viewMode: 1,

        data: {
            width: (minCroppedWidth + maxCroppedWidth) / 2,
            height: (minCroppedHeight + maxCroppedHeight) / 2
        },

        crop: function (event) {
            var width = event.detail.width;
            var height = event.detail.height;

            if (
                width < minCroppedWidth
                || height < minCroppedHeight
                || width > maxCroppedWidth
                || height > maxCroppedHeight
            ) {
                cropper.setData({
                    width: Math.max(minCroppedWidth, Math.min(maxCroppedWidth, width)),
                    height: Math.max(minCroppedHeight, Math.min(maxCroppedHeight, height))
                });
            }


        },
        cropmove: function () {
            var cropper = this.cropper;
            var cropBoxData = cropper.getCropBoxData();
            var h = 0;
            switch (ratio) {
                case 1:
                    h = (cropBoxData.width / 3) * 2;
                    break;
                case 2:
                    h = (cropBoxData.width / 16) * 9;
                    break;
                case 3:
                    h = (cropBoxData.width / 1) * 1;
                    break;
                default:
            }
            cropper.setCropBoxData({
                height: h
            });



        }
    });
}
function cameraError(message) {
    navigator.notification.alert(
        "Could not take a picture: " + message, // message
        onError, // callback
        'Game Over', // title
        'Ok'                  // buttonName
    );
}
function setOptions(srcType) {

    var options = {
        quality: 80,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: srcType,
        encodingType: Camera.EncodingType.JPEG,
        mediaType: Camera.MediaType.PICTURE,
        allowEdit: false,
        correctOrientation: true,
        saveToPhotoAlbum: true
    };
    return options;
}