// JavaScript Document


var PDFAnnotate = function(container_id, url, options = {}) {
	this.number_of_pages = 0;
	this.pages_rendered = 0;
	this.active_tool = 1; // 1 - Free hand, 2 - Text, 3 - Arrow, 4 - Rectangle
	this.fabricObjects = [];
	this.fabricObjectsData = [];
	this.color = '#212121';
	this.borderColor = '#000000';
	this.borderSize = 1;
	this.font_size = 16;
	this.active_canvas = 0;
	this.container_id = container_id;
	this.url = url;
	this.pageImageCompression = options.pageImageCompression
    ? options.pageImageCompression.toUpperCase()
    : "NONE";
	var inst = this;

	var loadingTask = pdfjsLib.getDocument(this.url);
	loadingTask.promise.then(function (pdf) {
		var scale = options.scale ? options.scale : 1.3;
	    inst.number_of_pages = pdf.numPages;

	    for (var i = 1; i <= pdf.numPages; i++) {
	        pdf.getPage(i).then(function (page) {
	            var viewport = page.getViewport({scale: scale});
	            var canvas = document.createElement('canvas');
	            document.getElementById(inst.container_id).appendChild(canvas);
	            canvas.className = 'pdf-canvas';
	            canvas.height = viewport.height;
	            canvas.width = viewport.width;
	            context = canvas.getContext('2d');

	            var renderContext = {
	                canvasContext: context,
	                viewport: viewport
				};
	            var renderTask = page.render(renderContext);
	            renderTask.promise.then(function () {
	                $('.pdf-canvas').each(function (index, el) {
	                    $(el).attr('id', 'page-' + (index + 1) + '-canvas');
	                });
	                inst.pages_rendered++;
	                if (inst.pages_rendered == inst.number_of_pages) inst.initFabric();
	            });
	        });
	    }
	}, function (reason) {
	    console.error(reason);
	});

}



PDFAnnotate.prototype.addImageToCanvas = function () {
	var inst = this;
	var fabricObj = inst.fabricObjects[inst.active_canvas];

	if (fabricObj) {
		var inputElement = document.createElement("input");
		inputElement.type = 'file'
		inputElement.accept = ".jpg,.jpeg,.png,.PNG,.JPG,.JPEG";
		inputElement.onchange = function() {
			var reader = new FileReader();
			reader.addEventListener("load", function () {
				inputElement.remove()
				var image = new Image();
				image.onload = function () {
					fabricObj.add(new fabric.Image(image))
				}
				image.src = this.result;
			}, false);
			reader.readAsDataURL(inputElement.files[0]);
		}
		document.getElementsByTagName('body')[0].appendChild(inputElement)
		inputElement.click()
	} 
}



function addImage(event) {
    event.preventDefault();
    pdf.addImageToCanvas()
}


/*
function showPdfData() {
    var string = pdf.serializePdf();
    $('#dataModal .modal-body pre').first().text(string);
    PR.prettyPrint();
    $('#dataModal').modal('show');
}
*/




//FIRMAS


(function () {
		   
    const canvas = document.querySelector('#firma-canvas');
    const ctx = canvas.getContext('2d');
	
	console.log('Se construye el canvas para la firma.');
	
	//Para rellenar el fondo blando del canvas, sino la firma tiene el bondo transparente/negro
	ctx.fillStyle = "#FFF";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(canvas, 0, 0);
	
	console.log('Se ha rellenado el canvas firma con el fondo blanco.');
	
	if (ctx) {
		ctx.lineWidth = 1;
		ctx.strokeStyle = '#000C7B';
	}
	else {
        console.log('No canvas :(');
        return;
    }

    const mappedEvents = {
        start: ['mousedown', 'touchstart'],
        move: ['mousemove', 'touchmove'],
        end: ['mouseup', 'touchend', 'touchcancel'],
    };
    let drawing = false;

    function addEventListeners(element, event, fn) {
        const evtArray = mappedEvents[event];

        if (!evtArray) {
            console.log('No events found :(');
            return;
        }

        const len = evtArray.length;

        for (let i = 0; i < len; ++i) {
            element.addEventListener(evtArray[i], fn, false);
        }
    }

    function onSigStart(ev) {
        // console.log('Signature starting');
        // console.log(ev.type);
        const coords = getOffset(ev);

        if (!coords) {
            return;
        }
		
		ctx?.beginPath();
        ctx?.moveTo(coords.x, coords.y);
		
        drawing = true;
    }

    function onSigMove(ev) {
        // console.log('Signature moving');
        // console.log(ev.type);
        if (!drawing) {
            return;
        }

        ev.preventDefault(); // to prevent scrolling when writing and window is scrollable

        const coords = getOffset(ev);

        if (!coords) {
            return;
        }

        ctx?.lineTo(coords.x, coords.y);
		ctx?.stroke();
    }

    function onSigEnd(ev) {
        // console.log('Signature ending');
        // console.log(ev.type);
        drawing = false;
    }

    function sigClear() {
        ctx?.clearRect(0, 0, canvas.width, canvas.height);
		//Para rellenar el fondo blando del canvas, sino la firma tiene el bondo transparente/negro
		ctx.fillStyle = "#FFF";
		ctx.fillRect(0, 0, canvas.width, canvas.height);
		ctx.drawImage(canvas, 0, 0);
    }

    function SavePicture(Refirma) {
		
		console.log('SavePicture');
		
		const dataURL=canvas.toDataURL('image/jpeg');
        console.log(dataURL);
        fetch(scriptGrabacion, { //scriptGrabacion esta definido global en el script principal
            "method":"POST",
            "headers":{
                "Content-Type":"application/text"
            },
            "body":dataURL
        }).then(function(response){
            return response.text();
        }).then(function(data){
			
			console.log('resultado grabacion archivo firma');
			console.log('es refirma: '+Refirma);
            console.log(data);
			
			archivoFirma=data; //archivoFirma esta definido global en el script principal, donde esta tb definida la funcion enviaFirma()
			
			enviaFirma(Refirma);
			
        })
    }

    function getOffset(ev) {
        const mEvent = ev;
        let x = 0;
        let y = 0;

        if (!mEvent.offsetX || !mEvent.offsetY) {
            const tEvent = ev;
            const touches = tEvent.touches;

            if (touches.length > 1) {
                return;
            }

            const touch = touches[0];
            const rect = ev.currentTarget.getBoundingClientRect();
            // x = touch.pageX - rect.x;
            // y = touch.pageY - rect.y;
            // should use clientX and clientY when scrolling is a possibility
            x = touch.clientX - rect.x;
            y = touch.clientY - rect.y;
        } else {
            x = mEvent.offsetX;
            y = mEvent.offsetY;
        }

        return {
            x: x / canvas.offsetWidth * canvas.width,
            y: y / canvas.offsetHeight * canvas.height,
        };
    }

    addEventListeners(canvas, 'start', onSigStart);
    addEventListeners(canvas, 'move', onSigMove);
    addEventListeners(canvas, 'end', onSigEnd);

    $(document).ready(function(){
							   
		var zoomOriginal=document.body.style.zoom;
		
		$('#firma-boton-borrar').on('click',function(){
			sigClear();
		});
		$('#firma-boton-cancelar').on('click',function(){
			sigClear();
			$('#firma_velo').hide();
			document.body.style.zoom=zoomOriginal;
		});
		$('#firma-boton-ok').on('click',function(){
			var Refirma=$(this).attr('Refirma');
			SavePicture(Refirma);
			$('#firma_velo').hide();
		});
	});


})();
			
