"use strict";

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

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

var _reactSortableHoc = require("react-sortable-hoc");

var _reactstrap = require("reactstrap");

var _arrayMove = _interopRequireDefault(require("array-move"));

var _html2canvas = _interopRequireDefault(require("html2canvas"));

var _guest = require("../../utils/apis/guest");

var _notifier = _interopRequireDefault(require("../../libs/notifier"));

var _globalFunc = require("../../utils/globalFunc");

var _FileRobotImageEditor = _interopRequireDefault(require("./FileRobotImageEditor"));

var _DeleteModal = _interopRequireDefault(require("./DeleteModal"));

var _LoaderButton = _interopRequireDefault(require("../LoaderButton"));

var _CustomSignature = _interopRequireDefault(require("../CustomSignature"));

var _CustomDragSignature = _interopRequireDefault(require("../CustomDragSignature"));

var _store = _interopRequireDefault(require("../../stores/store"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

const file_types = ['image/png', 'image/jpeg', 'image/jpg', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
let scrollPos = 0;

const CustomImageUpload = ({
  show,
  setShow,
  currentUser,
  files
}) => {
  const [scrollerHeight, setScrollerHeight] = (0, _react.useState)(0);
  const [selectedPage, setSelectedPage] = (0, _react.useState)(null);
  const [selectedPageIndex, setSelectedPageIndex] = (0, _react.useState)(0);
  const [leftScrollPos, setLeftScrollPos] = (0, _react.useState)(0);
  const [edit, toggleEdit] = (0, _react.useState)(false);
  const [showEditor, toggleEditor] = (0, _react.useState)(false);
  const [loading, setLoading] = (0, _react.useState)(false);
  const [pdf_images, setPdfImages] = (0, _react.useState)([]);
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [firstImage, setFirstImage] = (0, _react.useState)('');
  const [editImage, setEditImage] = (0, _react.useState)('');
  const [editImageIndex, setEditImageIndex] = (0, _react.useState)(null);
  const [pageToDelete, setPageToDelete] = (0, _react.useState)();
  const [deletePage, setDeletePage] = (0, _react.useState)();
  const [signature, setSignature] = (0, _react.useState)('');
  const [showSignature, setShowSignature] = (0, _react.useState)(false);
  const [dragable, setDragable] = (0, _react.useState)(true);
  const [b64, setB64] = (0, _react.useState)('');
  const [count, setCount] = (0, _react.useState)(0);
  const divEl = (0, _react.useRef)(null);
  const leftBar = (0, _react.useRef)(null);

  const setScrollHeight = () => {
    const height = document.getElementById('pdf-viewer-blk').clientHeight;
    setScrollerHeight(height);
  };

  const onScroll = () => {
    scrollPos = leftBar.current.scrollTop;
  };

  const toggleEditModal = () => toggleEdit(!edit); // const


  const toggleImageEditor = () => {
    toggleEditor(!showEditor);
  };

  (0, _react.useEffect)(() => {
    if (leftBar.current) {
      leftBar.current.scrollTop = leftScrollPos;
    }
  }, [selectedPage, selectedPageIndex, editImage]);

  const cancelEdit = e => {
    e.preventDefault();
    setShow();
  };

  const uploadAttachmentFile = async () => {
    let formData = new FormData();
    formData.append('file', files[0]);
    formData.append('user_id', currentUser);
    formData.append('images', pdf_images);
    const response = await (0, _guest.onUploadAttachment)(formData);
    toggleEditor();
    setShow(response.attachment);
  };

  const saveEdit = async e => {
    e.preventDefault();
    setIsLoading(true);
    await saveFileUpload();
    setIsLoading(false);
  };

  const saveFileUpload = async () => {
    let formData = new FormData();
    formData.append('file', files[0]);
    let all_images = [];
    pdf_images.map(image => {
      image = image.split('-');
      const ar2 = image.slice(1, image.length);
      const val = ar2.join('-');
      all_images.push('server/upload/' + val);
    });
    formData.append('user_id', currentUser);
    formData.append('pdf_images', all_images);
    const response = await (0, _guest.savePdf)(formData);

    if (response.success) {
      await uploadAttachmentFile();
    } else {// notify(string.eventAddingErr)
    }
  };

  const changeEditImage = async (fileObj, file) => {
    setLoading(true);

    try {
      const imageUrl = fileObj.imageBase64;
      const response = await (0, _guest.saveEditedFile)({
        imageUrl,
        name: selectedPage
      });

      if (response.success) {
        setpdfpagenames(response.images, 'image/jpeg', imageUrl);
        setSelectedPage(response.images[0]);
        setSignature('');
        setDragable(false);
      } else {// notify(string.eventAddingErr)
      }

      setLoading(false);
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  }; //On select image


  const onImageChange = async e => {
    try {
      const file = files[0];

      if ((0, _globalFunc.checkFileSize)(file)) {
        setShow();
        return;
      }

      if (file) {
        if (!file_types.includes(file.type)) {
          setShow();
          (0, _notifier.default)('Invalid Format');
          return false;
        } //Validate file size


        if (file.size > 3 * 1024 * 1024) {
          setShow();
          (0, _notifier.default)('File size should be less than 3MB');
          return false;
        }

        let fileArr = Array.from(files);

        if (!(file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/jpg') && fileArr.length > 1) {
          (0, _notifier.default)('Only Single Pdf can be selected');
          setShow();
          return false;
        }

        let response; //Upload DOCX

        if (file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
          let formData = new FormData();
          formData.append('file', file);
          formData.append('user_id', currentUser);
          response = await (0, _guest.convertDocument)(formData, 'docx');
        } //Upload PPTX


        if (file.type == 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
          let formData = new FormData();
          formData.append('file', file);
          formData.append('user_id', currentUser);
          response = await (0, _guest.convertDocument)(formData, 'pptx');
        } //Upload XLSX


        if (file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
          let formData = new FormData();
          formData.append('file', file);
          formData.append('user_id', currentUser);
          response = await (0, _guest.convertDocument)(formData, 'xlxs');
        } //Upload PDF


        if (file.type == 'application/pdf') {
          toggleEditModal();
          let formData = new FormData();
          formData.append('file', file);
          formData.append('user_id', currentUser);
          response = await (0, _guest.splitPdf)(formData);
          setFirstImage(response.base64);
        } //Upload Image


        if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/jpg') {
          toggleEditModal();
          const reader = new FileReader();
          reader.readAsDataURL(file);

          reader.onload = () => {
            setFirstImage(reader.result);
          };

          let formData = new FormData();

          for (let i = 0; i < fileArr.length; i++) {
            formData.append('file[]', fileArr[i]);
          }

          response = await (0, _guest.saveImages)(formData);
        }

        if (response.success) {
          setpdfpagenames(response.images, file.type, response.base64);
        } //  else {
        //   notify(string.eventAddingErr)
        // }
        // setLoading(false)

      }
    } catch (err) {// notify(err.message || err.toString())
    }
  };

  const _togglePageDelete = page => {
    setPageToDelete(page);
    setDeletePage(!deletePage);
  };

  const fileName = [...files].map(f => f.name).join(',');
  (0, _react.useEffect)(() => {
    onImageChange();
  }, [fileName]);
  /*Set pdf number sequencing*/

  const setpdfpagenames = (pages, type, b64) => {
    let pdf_arr = [];
    let sortedArr = [];

    if (type === 'image/png' || type === 'image/jpeg' || type === 'image/jpeg') {
      pages.forEach(page => {
        sortedArr.push(page);
      });
    } else {
      pages.forEach(page => {
        const nameArr = page.split('_');
        sortedArr[nameArr[2]] = page;
      });
    }

    if (sortedArr.length > 0) {
      let i = 1;
      sortedArr.forEach(val => {
        let name = i + '-' + val;
        pdf_arr.push(name);
        i++;
      });
      setPdfImages(pdf_arr);
      const firstPageName = pdf_arr[0].split('-');
      setSelectedPage(firstPageName[1]);

      if (b64) {
        let base64 = b64;

        if (b64.search('data:image/png;base64,') == -1 && b64.search('data:image/jpeg;base64,') == -1) {
          base64 = `data:image/png;base64,${b64}`;
        }

        setB64(base64);
      }
    }
  };

  const downloadFile = (base64, fileName) => {
    const mimetype = (0, _globalFunc.detectBase64MimeType)(base64);
    var a = document.createElement('a');
    a.href = mimetype + base64;
    a.download = fileName;
    a.click();
  };

  const printFile = (base64, file) => {
    const src = getImageUrl(`/${file}`);
    window.open(src, 'PRINT');
  };

  const _downloadAndPrintFile = async type => {
    const formData = new FormData();
    formData.append('file', files[0]);
    let all_images = [];
    pdf_images.map(image => {
      image = image.split('-');
      const ar2 = image.slice(1, image.length);
      const val = ar2.join('-');
      all_images.push('server/upload/' + val);
    });
    formData.append('user_id', currentUser);
    formData.append('pdf_images', all_images);
    const response = await (0, _guest.downloadImage)(formData);

    if (type == 'download') {
      downloadFile(response.base64, response.filename);
    } else if (type == 'print') {
      printFile(response.base64, response.file);
    }
  };

  const onSortEnd = async ({
    oldIndex,
    newIndex
  }) => {
    const newimage = (0, _arrayMove.default)(pdf_images, oldIndex, newIndex);
    setPdfImages(newimage);

    if (newIndex == 0 || oldIndex == 0) {
      let orderOfArray = newimage.map((img, index) => {
        const ar2 = img.split('-');
        return {
          index: index,
          name: ar2[1]
        };
      });
      await (0, _guest.onSortImages)({
        orderOfArray
      });
    }
  };

  const _deletePage = async () => {
    setLoading(true);
    const deleteImage = pdf_images[pageToDelete];
    const splitImage = deleteImage.split('-');
    const response = await (0, _guest.deleteFile)({
      file: splitImage[1]
    });

    if (response.success) {
      setpdfpagenames(response.images, 'image/jpeg', response.base64);
      setSelectedPage(response.images[0]); // if (pageToDelete == 0) {

      setFirstImage(response.base64); // }
    } else {// notify(string.eventAddingErr)
      }

    setLoading(false);

    _togglePageDelete(null);
  };

  const onDragableSave = () => {
    setDragable(false);
    const ele = document.getElementById('signature-update-image');
    const img = new Image();

    img.onload = () => {
      const height = img.height;
      const width = img.width;
      setTimeout(() => {
        (0, _html2canvas.default)(ele, {
          scale: 2
        }).then(canvas => {
          setLoading(true);
          const imgData = canvas.toDataURL();
          const img1 = new Image();

          img1.onload = e => {
            document.body.appendChild(img1);
            setTimeout(() => {
              (0, _html2canvas.default)(img1).then(resizedCanvas => {
                const resizedImage = resizedCanvas.toDataURL();
                setTimeout(async () => {
                  await changeEditImage({
                    imageBase64: resizedImage
                  });
                  setLoading(false);
                  setCount(1 + count);
                  const tempEle = document.getElementById('temp-image').remove();
                });
              });
            });
          };

          img1.id = "temp-image";
          img1.height = height;
          img1.width = width;
          img1.src = imgData;
        });
      });
    };

    img.src = getImageUrl(`/server/upload/${selectedPage}`);
  };

  const setSelectedImageFormURL = url => {
    (0, _globalFunc.toDataUrl)(url, b64 => {
      const base64 = b64.replace('data:application/octet-stream;base64', 'data:image/png;base64');
      setB64(base64);
    });
  };

  const getImageUrl = path => {
    return `${_store.default.state.rootURL}${path}?count=${count}`;
  };
  /*PDF image sorting case*/


  const SortableItem = (0, _reactSortableHoc.sortableElement)(({
    value,
    imageIndex
  }) => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("img", {
    onClick: () => {
      setLeftScrollPos(scrollPos);
      setSelectedPage(value);
      setSelectedPageIndex(imageIndex);
      setSelectedImageFormURL(getImageUrl(`/server/upload/${value}`));
    },
    key: value,
    src: getImageUrl(`/server/upload/${value}`),
    style: {
      zIndex: 99999999
    }
  })));
  const SortableList = (0, _reactSortableHoc.sortableContainer)(({
    items
  }) => {
    return /*#__PURE__*/_react.default.createElement("div", {
      id: "pdf-page-scroll",
      onScroll: onScroll,
      style: {
        height: scrollerHeight
      },
      ref: leftBar,
      className: "pdf-page-scroll"
    }, items.map((image, i) => {
      let img_number = image.split('-');
      const ar2 = img_number.slice(1, img_number.length);
      const val = ar2.join('-');
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
        key: i
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: selectedPage == val ? 'pdf-image active' : 'pdf-image'
      }, /*#__PURE__*/_react.default.createElement(SortableItem, {
        key: i,
        index: i,
        value: val,
        imageIndex: i
      }), /*#__PURE__*/_react.default.createElement("span", {
        className: "textnumber"
      }, img_number[0])));
    }));
  });
  let modalClass = "modal";

  if (show) {// modalClass += " show d-block";
  }

  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
    className: "col-md-12"
  }, edit && /*#__PURE__*/_react.default.createElement(_reactstrap.Modal, {
    isOpen: edit,
    id: "editPdfModal",
    size: "lg",
    style: {
      width: 900,
      height: 850
    },
    contentClassName: 'edit-filter-pdf-modal-content'
  }, /*#__PURE__*/_react.default.createElement(_reactstrap.ModalBody, {
    style: {
      width: '100%'
    }
  }, /*#__PURE__*/_react.default.createElement("div", {
    style: {
      height: 800,
      minWidth: 750
    }
  }, loading ? /*#__PURE__*/_react.default.createElement("div", {
    className: "split-pdf-loader"
  }, /*#__PURE__*/_react.default.createElement(_reactstrap.Spinner, {
    size: 'sm'
  }, " ", ' ', " ")) : /*#__PURE__*/_react.default.createElement("div", {
    id: "pdf-viewer-blk",
    className: "pdf-viewer",
    "data-height": scrollerHeight
  }, /*#__PURE__*/_react.default.createElement(SortableList, {
    axis: "xy",
    distance: 2,
    items: pdf_images,
    onSortEnd: onSortEnd,
    style: {
      zIndex: 99999999
    }
  }), /*#__PURE__*/_react.default.createElement("div", {
    className: "modal-header-blk"
  }, /*#__PURE__*/_react.default.createElement("h5", {
    className: "document-edit-title"
  }, "Edit PDF"), /*#__PURE__*/_react.default.createElement("div", {
    className: "document-action-btns"
  }, /*#__PURE__*/_react.default.createElement("i", {
    onClick: event => {
      event.stopPropagation();
      toggleImageEditor(true);
      setEditImage(getImageUrl(`/server/upload/${selectedPage}`));
      setEditImageIndex(selectedPageIndex);
    },
    style: {
      marginRight: '6px',
      cursor: 'pointer'
    },
    title: "Edit page",
    className: "fa fa-edit"
  }), pdf_images.length > 1 && /*#__PURE__*/_react.default.createElement("i", {
    onClick: () => _togglePageDelete(selectedPageIndex),
    style: {
      cursor: 'pointer'
    },
    title: "Delete page",
    className: "fa fa-trash-alt mr-2"
  }), pdf_images.length && /*#__PURE__*/_react.default.createElement("i", {
    onClick: () => _downloadAndPrintFile('print'),
    style: {
      cursor: 'pointer'
    },
    title: "Print attachment",
    className: "fa fa-print mr-2"
  }), pdf_images.length && /*#__PURE__*/_react.default.createElement("i", {
    onClick: () => _downloadAndPrintFile('download'),
    style: {
      cursor: 'pointer'
    },
    title: "Download attachment",
    className: "fa fa-download"
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "edit-doc-close-btn"
  }, /*#__PURE__*/_react.default.createElement("button", {
    onClick: toggleEditModal,
    type: "button",
    className: "close btn btn-primary",
    "aria-label": "Close"
  }, /*#__PURE__*/_react.default.createElement("span", {
    "aria-hidden": "true"
  }, "\xD7")), /*#__PURE__*/_react.default.createElement("button", {
    className: "close",
    onClick: e => {
      e.preventDefault();
      setShowSignature(true);
    }
  }, "Add Signature"))), /*#__PURE__*/_react.default.createElement("div", {
    ref: divEl,
    className: "pdf-page-view"
  }, !!selectedPage && !!b64 && /*#__PURE__*/_react.default.createElement("div", {
    id: "signature-update-image",
    className: "image-wrapper",
    style: {
      display: 'inline-block'
    }
  }, /*#__PURE__*/_react.default.createElement("img", {
    key: selectedPage,
    onLoad: setScrollHeight,
    src: b64
  }), !!signature && /*#__PURE__*/_react.default.createElement(_CustomDragSignature.default, {
    defaultValue: signature,
    onSave: onDragableSave,
    read_only: false,
    isDragable: dragable,
    index: 1
  }))), /*#__PURE__*/_react.default.createElement("div", {
    className: "modal-footer mr-5 mb-5"
  }, /*#__PURE__*/_react.default.createElement("button", {
    className: "btn btn-secondary",
    onClick: cancelEdit
  }, "Cancel"), /*#__PURE__*/_react.default.createElement(_LoaderButton.default, {
    cssClass: "btn btn-primary btn-fix-width",
    onClick: saveEdit,
    isLoading: isLoading,
    text: "Save"
  })))))), /*#__PURE__*/_react.default.createElement(_DeleteModal.default, {
    toggle: () => _togglePageDelete(null),
    isOpen: deletePage,
    onDeleteEntry: _deletePage
  }), !!showSignature && /*#__PURE__*/_react.default.createElement(_CustomSignature.default, {
    onCancel: () => setShowSignature(false),
    updateSignature: dataURL => {
      setShowSignature(false);
      setDragable(true);
      setSignature(dataURL);
    }
  })), showEditor && /*#__PURE__*/_react.default.createElement(_FileRobotImageEditor.default, {
    changeEditImage: changeEditImage,
    show: showEditor,
    setShow: toggleImageEditor,
    editImage: editImage
  }));
};

var _default = CustomImageUpload;
exports.default = _default;