/*
 * 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 bsnumpad(title, content, okbtn, cancelbtn, callback) {
    var html = '<div class="modal fade" id="bsnumpad">'
            + '  <div class="modal-dialog">'
            + '    <div class="modal-content">'
            + '      <div class="modal-header">'
            + '        <h5 class="modal-title" id="bsnumpad-title"></h5>'
            + '        <button type="button" class="close" data-dismiss="modal" aria-label="Close">'
            + '          <span aria-hidden="true">&times;</span>'
            + '        </button>'
            + '      </div>'
            + '      <div class="modal-body" id="bsnumpad-body">'
            + '        <div class="display-4 text-center">&nbsp;<span id="bsnumpad-input"></span>&nbsp;</div>'
            + '        <div id="bsnumpad-pad" class="row"></div>'
            + '      </div>'
            + '      <div class="modal-footer">'
            + '        <button type="button" class="btn btn-secondary" data-dismiss="modal" id="bsnumpad-cancel">Cancel</button>'
            + '        <button type="button" class="btn btn-primary" id="bsnumpad-ok">OK</button>'
            + '      </div>'
            + '    </div>'
            + '  </div>'
            + '</div>';
    $("body").append(html);
    function addButton(val, label) {
        $("#bsnumpad-pad").append('<div class="col-4 p-1"><div class="w-100 h-100 p-2 py-3 btn btn-default numpadbtn" data-key="' + val + '"><h5>' + label + '</h5></div></div>');
    }
    for (var i = 1; i <= 9; i++) {
        addButton(i, i);
    }
    addButton('0', '0');
    addButton('.', '.');
    addButton('clear', '<i class="fas fa-eraser"></i>');
    $("#bsnumpad-pad").on("click", ".numpadbtn", function () {
        var char = $(this).data('key');
        var val = $("#bsnumpad-input").text();
        if (char == "clear") {
            val = "";
        } else if (char == ".") {
            if (!val.includes('.')) {
                val += char;
            }
        } else {
            val += char;
        }
        $("#bsnumpad-input").text(val);
    });
    $("#bsnumpad-title").html(title);
    $("#bsnumpad-input").text(content);
    $("#bsnumpad-ok").html(okbtn);
    $("#bsnumpad-cancel").html(cancelbtn);
    $("#bsnumpad-ok").on("click", function () {
        callback($("#bsnumpad-input").text());
        $("#bsnumpad").modal("hide");
    });
    $("#bsnumpad").on("shown.bs.modal", function () {
        $("#bsnumpad-input").focus();
    });
    $("#bsnumpad").on("hidden.bs.modal", function () {
        $("#bsnumpad").remove();
    });
    $("#bsnumpad").modal("show");
}