import './drawing.scss';
import cloneDeep from 'lodash/cloneDeep';

const icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="-8 -8 40 40">\n' +
  '  <path d="m8.684,23.485c-.183.329-.523.515-.875.515-.164,0-.331-.04-.485-.126C2.669,21.288,0,16.96,0,12,0,5.383,5.383,0,12,0c.731,0,1.465.066,2.181.198.543.1.903.621.803,1.164-.1.544-.622.905-1.164.803-.597-.109-1.208-.165-1.819-.165C6.486,2,2,6.486,2,12c0,4.213,2.294,7.903,6.295,10.126.482.269.657.877.388,1.359Zm15.119-13.666c-.099-.543-.618-.907-1.164-.803-.543.1-.903.621-.803,1.164.109.595.165,1.207.165,1.819,0,3.309-2.691,6-6,6s-6-2.691-6-6c0-.553-.448-1-1-1s-1,.447-1,1c0,4.411,3.589,8,8,8s8-3.589,8-8c0-.733-.066-1.467-.198-2.181Zm-10.63-3.233L18.879.879c1.133-1.133,3.109-1.133,4.243,0,1.169,1.17,1.169,3.072,0,4.242l-5.707,5.707c-.755.756-1.76,1.172-2.828,1.172h-1.586c-.552,0-1-.447-1-1v-1.586c0-1.068.417-2.073,1.172-2.828Zm.828,3.414h.586c.526,0,1.042-.214,1.414-.586l5.707-5.707c.39-.39.39-1.024,0-1.414-.378-.379-1.037-.379-1.414,0l-5.708,5.707c-.378.378-.586.88-.586,1.414v.586Z"/>\n' +
  '</svg>';

const content = '' +
  '<!DOCTYPE html><html><head> <meta charset="UTF-8"/> <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script> <script type="text/javascript" src="https://unpkg.com/@excalidraw/excalidraw@0.16.1/dist/excalidraw.production.min.js"></script></head><body class="excalidraw-container"><div id="app"></div><style> body { display: flex; width: 100vw; height: 100vh; padding: 0; margin: 0;}#app { flex-grow: 1;}.excalidraw .App-menu_top > .Stack.Stack_vertical > div:first-child, .excalidraw .disable-zen-mode, .excalidraw .layer-ui__wrapper__footer-right, .excalidraw .layer-ui__wrapper__github-corner, .excalidraw button.ToolIcon_type_button.ToolIcon.ToolIcon_size_m.Shape.ToolIcon_type_button--show, .excalidraw .library-menu-items-container__items .library-menu-items-container__header, .excalidraw .library-menu-control-buttons, .excalidraw .ToolIcon__library { display: none;} </style><script type="text/javascript"> const App = () => { const data = window.saveData || {}; return React.createElement(React.Fragment, null, React.createElement("div", {style: {height: "100%"},}, React.createElement(ExcalidrawLib.Excalidraw, { initialData: { elements: data.elements || [], files: data.files || [], libraryItems: data.libraryItems || [], appState: {zenModeEnabled: false, theme: localStorage.itfTheme}, scrollToContent: false }, onChange: (elements, state, files) => { window.saveData = window.saveData || {}; window.saveData.elements = elements; window.saveData.files = files; ExcalidrawLib.exportToSvg({ elements, state, files }).then(svg => { svg.removeAttribute(\'width\'); svg.removeAttribute(\'height\'); window.saveData.svg = svg.outerHTML; }); }, onLibraryChange: (items) => { window.saveData = window.saveData || {}; window.saveData.libraryItems = items; } })));};const excalidrawWrapper = document.getElementById("app");const root = ReactDOM.createRoot(excalidrawWrapper);root.render(React.createElement(App)); </script></body></html>';

export default class Drawing {
  data = null;
  readOnly = false;

  static get sanitize(){
    return {
      svg: true,
      files: true,
      caption: {} // only tags from Inline Toolbar
    }
  }

  /**
   * Allow to use this tool in read only mode
   */
  static get isReadOnlySupported() {
    return true;
  }

  constructor({ data, readOnly }){
    this.data = data;
    this.readOnly = readOnly;
  }

  static get toolbox() {
    return {
      title: 'Drawing',
      icon
    };
  }
  render(){
    const wrapper = createWrapper(this.data, this.readOnly);
    if (!this.readOnly) {
      wrapper.classList.remove('readonly');
      wrapper.addEventListener('dblclick', async () => {
        const modal = document.createElement('div');
        modal.classList.add('itf-modal');
        modal.classList.add('modal');
        modal.classList.add('fade');
        modal.classList.add('editorjs-drawing-modal');
        const modalDialog = document.createElement('div');
        modalDialog.classList.add('modal-dialog');
        modalDialog.classList.add('modal-fullscreen');
        const modalContent = document.createElement('div');
        modalContent.classList.add('modal-content');
        const modalHeader = document.createElement('div');
        modalHeader.classList.add('modal-header');
        const modalTitle = document.createElement('h5');
        modalTitle.classList.add('modal-title');
        modalTitle.textContent = 'Drawing';
        modalHeader.appendChild(modalTitle);
        const btnHolder = document.createElement('div');
        btnHolder.classList.add('d-flex');
        const modalSaveBtn = document.createElement('button');
        modalSaveBtn.classList.add('btn');
        modalSaveBtn.classList.add('btn-primary');
        modalSaveBtn.classList.add('itf-button');
        modalSaveBtn.textContent = 'Save & Close';
        const modalCancelBtn = document.createElement('button');
        modalCancelBtn.classList.add('btn');
        modalCancelBtn.classList.add('btn-secondary');
        modalCancelBtn.classList.add('itf-button');
        modalCancelBtn.classList.add('me-2');
        modalCancelBtn.textContent = 'Cancel';
        btnHolder.appendChild(modalCancelBtn);
        btnHolder.appendChild(modalSaveBtn);
        modalHeader.appendChild(modalTitle);
        modalHeader.appendChild(btnHolder);
        modalContent.appendChild(modalHeader);
        const modalBody = document.createElement('div');
        modalBody.classList.add('modal-body');
        const iframe = document.createElement('iframe');
        modalBody.appendChild(iframe);
        modalContent.appendChild(modalBody);
        modalDialog.appendChild(modalContent);
        modal.appendChild(modalDialog);
        document.body.appendChild(modal);
        const {default: Modal} = await import('../../../modal/modalSrc');
        const modalEl = new Modal(modal, {context: document.body, backdrop: 'static'});
        modalEl.show();
        modal.addEventListener('hidden.bs.modal', () => {
          document.body.removeChild(modal);
        });

        iframe.classList.add('modal-body-content');
        iframe.contentWindow.document.open();
        iframe.contentWindow.document.write(content);
        iframe.contentWindow.document.close();

        iframe.contentWindow.saveData = cloneDeep(this.data);
        console.info(this.data, iframe.contentWindow.saveData);
        modalSaveBtn.addEventListener('click', () => {
          this.data = iframe.contentWindow.saveData;
          if (this.data.svg) {
            createSvg(wrapper, this.data, this.readOnly);
          }
          modalEl.hide();
        });
        modalCancelBtn.addEventListener('click', () => {
          modalEl.hide();
        });
      });
    } else {
      wrapper.classList.add('readonly');
    }
    return wrapper;

    function createWrapper(data, readOnly) {
      const wrapper = document.createElement('div');
      wrapper.classList.add('editorjs-drawing');
      if (data.svg) {
        wrapper.classList.remove('empty');
        createSvg(wrapper, data, readOnly);
      } else if (!readOnly) {
        wrapper.classList.add('empty');
        wrapper.innerHTML = `<div class="text-muted icon">${icon}</div><div class="text-muted text">Double click to start sketching out your thoughts.</div>`;
      }
      return wrapper;
    }

    function createSvg(wrapper, { svg, caption }, readOnly) {
      const svgContainer = document.createElement('div');
      svgContainer.innerHTML = svg.replace(/@undefined/g, '@0.16.1'); // глючить версія в excalidraw

      const divSvg = document.createElement('div');
      wrapper.innerHTML = '';
      wrapper.classList.remove('empty');
      wrapper.appendChild(divSvg);

      const shadow = divSvg.attachShadow({ mode: "open" });
      shadow.appendChild(svgContainer.childNodes[0]);

      const captionEl = document.createElement('div');
      captionEl.contentEditable = !readOnly;
      captionEl.classList.add('editorjs-drawing-caption');
      captionEl.textContent = caption;
      if (!readOnly) {
        captionEl.setAttribute('data-text', 'Caption');
        captionEl.addEventListener('dblclick', (e) => {
          e.stopPropagation();
        });
      }
      wrapper.appendChild(captionEl);
    }
  }
  save(blockContent){
    const caption = blockContent.querySelector('[contenteditable]');
    const data = cloneDeep(this.data);
    data.caption = caption ? caption.innerHTML : '';
    return data;
  }
}
