import SignaturePad from 'signature_pad';

wsSignaturePadController.$inject = [
  '$scope',
  '$window',
  '$element',
];

export default function wsSignaturePadController($scope, $window, $element) {
  const vm = this;
  let canvas;
  let canvasContainer;
  let signaturePad;

  vm.$onInit = () => {
    Object.assign($scope, {
      state: {
        isEdited: false,
        isSaved: false,
        signatureData: null,
      },
      clear,
      save,
      redo,
    });

    _initialize();
  };

  vm.$onDestroy = () => {
    angular.element($window).off('resize', _resizeCanvas);
  };

  function _initialize() {
    canvas = $element.find('canvas')[0];
    canvasContainer = $element.find('.signature-pad-body')[0];
    signaturePad = new SignaturePad(canvas, { onEnd: isEdited });
    angular.element($window).on('resize', _resizeCanvas);
    _resizeCanvas();
  }

  function _resizeCanvas() {
    canvas.width = canvasContainer.offsetWidth;
    canvas.height = canvasContainer.offsetHeight;
  }

  function isEdited() {
    $scope.state.isEdited = true;
    $scope.$digest();
  }

  function clear() {
    signaturePad.clear();
    $scope.state.isEdited = false;
  }

  function save() {
    const signatureData = signaturePad.toDataURL();
    vm.onSave({ signatureData });
    signaturePad.off();
    $scope.state.isSaved = true;
  }

  function redo() {
    signaturePad.on();
    signaturePad.clear();
    vm.onRedo();
    $scope.state.isSaved = false;
    $scope.state.isEdited = false;
  }
}
