"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireDefault(require("react"));

var _reactSignatureCanvas = _interopRequireDefault(require("react-signature-canvas"));

var _propTypes = _interopRequireDefault(require("prop-types"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

var canvasOptions = {
  height: 300,
  width: 500
};

function Signature(props) {
  var sigPad = _react["default"].useRef();

  var uploadedFile = _react["default"].useRef();

  var clearOnBegin = _react["default"].useRef();

  var library = props.library,
      attributes = props.attributes,
      control = props.control;
  var style = control.containerstyle ? control.containerstyle : {
    display: 'flex'
  };
  var BUTTON = library.Button;
  var enableUpload = control.enableupload || false;

  var clear = function clear() {
    sigPad.current.clear();
    props.onChange(props.control, '');
    if (uploadedFile && uploadedFile.current) uploadedFile.current.value = null;
  };

  var onEnd = function onEnd() {
    props.onChange(props.control, sigPad.current.toDataURL('image/png', 1.0));
  };

  var handleFileSelect = function handleFileSelect(e) {
    e.preventDefault();
    var files = e.target.files || e.dataTransfer.files || [];

    if (files.length > 0) {
      var file = files[0];

      if (file.size > 1048576) {
        alert('File is too big!.You can upload file more than 1mb..');
        setTimeout(function () {
          uploadedFile.current.value = null;
          sigPad.current.clear();
        }, 10);
      } else {
        getBase64(file).then(function (data) {
          sigPad.current.clear();
          sigPad.current.fromDataURL(data, canvasOptions);
        });
      }
    }
  };

  var getBase64 = function getBase64(file) {
    return new Promise(function (resolve, reject) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = function () {
        return resolve(reader.result);
      };

      reader.onerror = function (error) {
        return reject(error);
      };
    });
  };

  var validUrl = function validUrl(url) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
    return regexp.test(url);
  };

  var convertImgToBase64 = function convertImgToBase64(url, callback) {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.crossOrigin = 'Anonymous';

    img.onload = function () {
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0);
      var dataURL = canvas.toDataURL('image/png');
      callback.call(this, dataURL, {
        height: img.height,
        width: img.width
      }); // Clean up

      canvas = null;
    };

    img.src = url;
  };

  _react["default"].useEffect(function () {
    if (attributes.value && validUrl(attributes.value)) {
      convertImgToBase64(attributes.value, function (data, options) {
        clearOnBegin.current = true;
        sigPad.current.clear();
        sigPad.current.fromDataURL(data, options);
      });
    } else if (attributes.value) {
      sigPad.current.fromDataURL(attributes.value, attributes.canvasProps);
    }
  }, []);

  var onBegin = function onBegin() {
    if (clearOnBegin.current) {
      sigPad.current.clear();
      clearOnBegin.current = false;
    }
  };

  return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", {
    style: style
  }, /*#__PURE__*/_react["default"].createElement(_reactSignatureCanvas["default"], _extends({
    ref: sigPad
  }, attributes, {
    onEnd: onEnd
  }))), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      display: 'flex',
      margin: '1rem',
      "float": 'right'
    }
  }, enableUpload && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("input", {
    key: Date.now(),
    accept: "image/*",
    style: {
      display: 'none'
    },
    id: "contained-button-file",
    multiple: false,
    type: "file",
    onChange: handleFileSelect,
    ref: uploadedFile
  }), /*#__PURE__*/_react["default"].createElement("label", {
    htmlFor: "contained-button-file"
  }, /*#__PURE__*/_react["default"].createElement(BUTTON, {
    variant: "contained",
    color: "primary",
    component: "span"
  }, "Upload"))), /*#__PURE__*/_react["default"].createElement(BUTTON, {
    variant: "contained",
    color: "primary",
    style: {
      marginLeft: '1rem'
    },
    onClick: clear
  }, "Clear")));
}

Signature.propTypes = process.env.NODE_ENV !== "production" ? {
  attributes: _propTypes["default"].object,
  library: _propTypes["default"].object,
  component: _propTypes["default"].string.isRequired,
  onChange: _propTypes["default"].func,
  control: _propTypes["default"].object
} : {};
Signature.defaultProps = {
  attributes: null,
  library: null,
  onChange: null,
  control: {}
};
var _default = Signature;
exports["default"] = _default;