/*
 * Copyright 2021 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 activeDrawImage;
var signaturePadCallback = function () {};
var clientSignatureSvg = "";

function getStampSvg(callback) {
    getStampSvgWithValues({
        name: getStorage("notary_name"),
        location: getStorage("notary_location"),
        expires: getStorage("notary_expires"),
        idnumber: getStorage("notary_idnumber"),
        state: getStorage("notary_state")
    }, callback);
}

function getStampSvgWithValues(values, callback) {
    $.get("templates/stamps/" + values.state + ".svg", {}, function (data) {
        data = data + "";
        data = data.replaceAll("[[[NAME]]]", values.name);
        data = data.replaceAll("[[[LOCATION]]]", values.location);
        data = data.replaceAll("[[[EXPIRES]]]", values.expires);
        data = data.replaceAll("[[[IDNUMBER]]]", values.idnumber);

        callback(data);
    }, "text");
}

function makeStampImage(callback) {
    getStampSvg(function (data) {
        svgToImage(data, function (err, image) {
            if (err) {
                callback(false);
                return;
            }
            callback(image);
        });
    });
}

function activateTextTool() {
    if (!canUseDrawTools()) {
        showToast("Please open a document first.");
        return;
    }
    var text = prompt("Enter a line of text to add to the document:");
    if (text == "" || text == null) {
        return;
    }
    var canvas = document.createElement('canvas');
    canvas.width = 2000;
    canvas.height = 400;
    var ctx = canvas.getContext('2d');

    ctx.font = "50px sans-serif";
    ctx.fillText(text, 0, 50);

    const image = new Image();
    image.src = canvas.toDataURL();
    image.width = 500;
    image.height = 100;

    activeDrawImage = image;

    image.onload = function () {
        enableGuideBox(activeDrawImage);
    };
}

function activateStampDrawTool() {
    if (!canUseDrawTools()) {
        showToast("Please open a document first.");
        return;
    }
    makeStampImage(function (image) {
        activeDrawImage = image;
        enableGuideBox(image);
    });
}

function activateNotarySignatureTool() {
    if (!canUseDrawTools()) {
        showToast("Please open a document first.");
        return;
    }
    if (!inStorage("notary_signature")) {
        showAlert("Please set a notary signature in the settings.");
        return;
    }
    svgToImage(getStorage("notary_signature"), function (err, image) {
        if (err) {
            callback(false);
            return;
        }
        activeDrawImage = image;
        enableGuideBox(image);
    });
}

function activateNotaryCertificateTool() {
    if (!canUseDrawTools()) {
        showToast("Please open a document first.");
        return;
    }
    initCertificateBuilder();

    certificateBuilderCallback = function () {
        getCertificateSvg(function (svg) {
            svgToImage(svg, function (err, image) {
                if (err) {
                    console.error(err);
                    return;
                }
                activeDrawImage = image;
                enableGuideBox(image);
            });
        });
    };
}

function activateClientSignaturePad() {
    if (!canUseDrawTools()) {
        showToast("Please open a document first.");
        return;
    }
    initSignaturePad();
    signaturePadCallback = function () {
        if (clientSignatureSvg != "" && signaturePad.isEmpty()) {
            var signature = clientSignatureSvg;
        } else {
            var signature = signaturePad.toDataURL("image/svg+xml");
            signature = signature.replace("data:image/svg+xml;base64,", "");
            signature = atob(signature);
            signature = trimAndShrinkSVG(signature);
            clientSignatureSvg = signature;
        }

        svgToImage(signature, function (err, image) {
            if (err) {
                callback(false);
                return;
            }
            activeDrawImage = image;
            enableGuideBox(image);
        });
    };
}

function drawImageFromUrl(x, y, width, height, src, canvas) {
    var ctx = canvas.getContext("2d");
    const image = new Image();
    image.src = src;
    image.onload = () => {
        ctx.drawImage(image, x, y, width, height);
    }
}

function drawImage(x, y, width, height, image, canvas) {
    var ctx = canvas.getContext("2d");
    ctx.drawImage(image, x, y, width, height);
}

$("#page-canvas-container").on("click", ".page-canvas", function (evt) {
    $("#page-canvas-container .page-canvas").removeClass("active");
    $(this).addClass("active");
    evt.stopPropagation();
});

$("body").on("click", "#page-canvas-container", function (evt) {
    $("#page-canvas-container .page-canvas").removeClass("active");
    disableGuideBox();
});

$("#page-canvas-container").on("click", ".page-canvas.active", function (evt) {
    if (typeof activeDrawImage == "undefined" || activeDrawImage == null) {
        return;
    }
    var canvas = $(this)[0];
    var coords = getMousePos(canvas, evt);

    var imageWidth = (activeDrawImage.width / 96) * pdfAssumedDPI * pdfPageScale;
    var imageHeight = (activeDrawImage.height / 96) * pdfAssumedDPI * pdfPageScale;
    drawImage(coords.x, coords.y, imageWidth, imageHeight, activeDrawImage, canvas);
});


function enableGuideBox(image, scalecorrectionfactor) {
    $("#cancelDrawBtn").removeClass("disabled");
    if (typeof scalecorrectionfactor == "undefined") {
        scalecorrectionfactor = 1;
    }
    var context = $("#placementguidebox")[0].getContext('2d');
    context.clearRect(0, 0, $("#placementguidebox")[0].width, $("#placementguidebox")[0].height);
    $("#placementguidebox").css("display", "");
    // calculate size of guide image
    var pageWidthPx = $("#page-canvas-container .page-canvas")[0].getContext("2d").canvas.width;
    var pageCanvasCurrentWidthPx = $("#page-canvas-container .page-canvas").css("width").replace("px", "") * 1;
    var pageWidthInches = pageWidthPx / (pdfAssumedDPI * pdfPageScale);
    var canvasCurrentDPI = pageCanvasCurrentWidthPx / pageWidthInches;

    var imageWidth = (image.width / (96 * scalecorrectionfactor)) * canvasCurrentDPI;
    var imageHeight = (image.height / (96 * scalecorrectionfactor)) * canvasCurrentDPI;

    var canvas = $("#placementguidebox")[0];
    canvas.width = imageWidth;
    canvas.height = imageHeight;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0, imageWidth, imageHeight);
}

function disableGuideBox() {
    $("#placementguidebox").css("display", "none");
    $("#cancelDrawBtn").addClass("disabled");

    var context = $("#placementguidebox")[0].getContext('2d');
    context.clearRect(0, 0, $("#placementguidebox")[0].width, $("#placementguidebox")[0].height);
    activeDrawImage = null;
}

$("#page-canvas-container").on("mousemove", function (e) {
    var posx = 0;
    var posy = 0;
    posx = e.pageX + $("#page-canvas-container").scrollLeft() - $("#page-canvas-container").offset().left;
    posy = e.pageY + $("#page-canvas-container").scrollTop() - $("#page-canvas-container").offset().top;
    $("#placementguidebox").css({
        left: posx,
        top: posy
    });
});

/**
 * https://stackoverflow.com/a/17130415
 * @param {type} canvas
 * @param {type} evt
 * @returns {getMousePos.pdfAnonym$1}
 */
function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect(), // abs. size of element
            scaleX = canvas.width / rect.width, // relationship bitmap vs. element for X
            scaleY = canvas.height / rect.height;  // relationship bitmap vs. element for Y

    return {
        x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have
        y: (evt.clientY - rect.top) * scaleY     // been adjusted to be relative to element
    }
}

/**
 * Returns true if drawing tools should be available (i.e. there's a document to draw on)
 * @returns {Boolean}
 */
function canUseDrawTools() {
    return $("#page-canvas-container .page-canvas").length > 0;
}

// Hide it at start
// doesn't work in CSS because of reasons
disableGuideBox();