App.DigitalSignature = {
  init: function(canvas) {
    var signatureInput = $(canvas).data("signature-input");
    var $clearButton   = $("[data-behavior=clear-digital-signature]")

    var opts = {
      onEnd: function() { 
        // Save the signature to an input field
        if ($(signatureInput).length) {
          $(signatureInput).val(signaturePad.crop().toDataURL());
        }
      }
    };

    // Initialize using SignaturePad plugin
    var signaturePad = new SignaturePad(canvas, opts);

    // Handler for when the browser window is resized
    // Stores the current signature and restores it after the resizing
    function resizeCanvas() {
      var cachedSignature = null;

      if (!signaturePad.isEmpty()) {
        var cachedSignature = signaturePad.toDataURL();
      }

      var ratio =  Math.max(window.devicePixelRatio || 1, 1);
      canvas.width = canvas.offsetWidth * ratio;
      canvas.height = canvas.offsetHeight * ratio;
      canvas.getContext("2d").scale(ratio, ratio);
      signaturePad.clear(); // otherwise isEmpty() might return incorrect value

      if (cachedSignature !== null) {
        signaturePad.fromDataURL(cachedSignature);
      }
    }

    // Attach resize handler and trigger it once for an initial sizing
    window.addEventListener("resize", resizeCanvas);
    resizeCanvas();

    // Attach clear button handler
    $clearButton.on("click", function(e) {
      e.preventDefault();
      signaturePad.clear();
      $(signatureInput).val("");
    });
  },
};

$(document).on("turbolinks:load", function() {
  $("[data-behavior=digital-signature]").each(function(index, element) {
    App.DigitalSignature.init(element);
  });
});
