/*
 * 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/.
 */

function getCertificateSvg(callback) {
    // Allow for states with unusual certificate requirements by overriding the path to a subfolder
    var state = "";
    switch (getStorage("notary_state")) {
        case "yz":
            state = "yz/";
            break;
        default:
            state = "";
    }
    var path = state + "generic.svg";
    var act = $("#certificateBuilderModal #cert_act option:selected").val();

    if (act == "CERTIFIEDCOPYELECTRONIC") {
        path = state + "certifiedcopyelectronic.svg";
    }
    getCertificateSvgWithValues(path, {
        name: getStorage("notary_name"),
        location: getStorage("notary_location"),
        expires: getStorage("notary_expires"),
        idnumber: getStorage("notary_idnumber"),
        state: $("#certificateBuilderModal #cert_state option:selected").val(),
        county: $("#certificateBuilderModal #cert_county").val(),
        act: act,
        date: formatTimestamp("F j, Y"),
        signer: $("#certificateBuilderModal #cert_signer").val(),
        pagecount: $("#page-canvas-container .page-canvas").length,
        doctitle: pdfTitle == "" ? "(untitled)" : pdfTitle
    }, callback);
}

function getCertificateSvgWithValues(path, values, callback) {
    $.get("templates/certificates/" + path, {}, function (svg) {
        svg = svg + "";
        for (const key in values) {
            svg = svg.replaceAll("[[[" + key.toUpperCase() + "]]]", values[key]);
        }

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

function initCertificateBuilder() {
    /**
     * Load state dropdown with default of notary state
     */
    $("#cert_state").html("");
    for (const abbrev in STATE_ABBREV) {
        var selected = "";
        if (abbrev == getStorage("notary_state").toUpperCase()) {
            selected = " selected";
        }
        $("#cert_state").append("<option value=\"" + STATE_ABBREV[abbrev] + "\"" + selected + ">" + STATE_ABBREV[abbrev] + "</option>");
    }

    new bootstrap.Modal(document.getElementById('certificateBuilderModal')).show();
}

$("body").on("input change paste select", "#certificateBuilderModal input,#certificateBuilderModal select", function () {
    getCertificateSvg(function (svg) {
        $("#certificateBuilderModal #certificate-preview").attr("src", "data:image/svg+xml;base64," + btoa(svg));
    });
});