import { setInputNative } from '@content/service/util';

const configElement = {
  inputTitle: 'div.edit-main > div > div > div > div > div > input',
  descriptionHtml: 'div.editor-outer > div > div.ql-editor',
  descriptionTextarea: 'div.eds-input.eds-input__area > textarea',
  descriptionInput: '',
  listImageDescription: 'div.editor-outer > div > div.ql-editor > p > img',
  containerDescription: 'div.panel-content-wrapper > div > div > div.edit-row.description-wrap > div.edit-main > div',
};

const getDescriptionType = () => {
  if (document.querySelector(configElement.descriptionHtml)) {
    return 'html';
  }

  if (document.querySelector(configElement.descriptionTextarea)) {
    return 'text';
  }

  return '';
};

export const getDescriptionInput = () => document.querySelector(configElement.descriptionHtml) || document.querySelector(configElement.descriptionTextarea);

export const getProductName = () => document.querySelector(configElement.inputTitle).value;

export const getProductDescription = () => {
  const descriptionType = getDescriptionType();

  if (descriptionType === 'html') {
    return getDescriptionInput().innerHTML;
  }

  if (descriptionType === 'text') {
    return getDescriptionInput().value;
  }

  return '';
};

export const getListImageDescription = () => {
  const descriptionType = getDescriptionType();

  if (descriptionType === 'html') {
    return [...document.querySelectorAll(configElement.listImageDescription)].map((item) => item.src);
  }

  return [];
};

export const setProductDescription = (description) => {
  const descriptionType = getDescriptionType();

  if (descriptionType === 'html') {
    getDescriptionInput().innerHTML = description.replace(/\n/g, '<br/>');
  }

  if (descriptionType === 'text') {
    setInputNative(getDescriptionInput(), description.replace(/\n/g, '\n\n'));
  }
};
