import { JiraCodeToRTECodeBlockStrategy } from './jira-code-to-rte-code-block-strategy';
/** Transform vega-code-block element to code block DTO */
export class VegaCodeBlockToRTECodeBlockStrategy extends JiraCodeToRTECodeBlockStrategy {
  /**
   * Can be handle.
   *
   * TODO: Update the browser clipboard data to fix the issue with nested vega-code-block elements.
   * In safari the html snippet will be like: <vega-code-block><p><span>paragraph</span></p><vega-code-block></vega-code-block></vega-code-block>
   * The vega-code-block nested inside the vega-code-block, so we need to check the child element.
   *
   * @param {HTMLElement[]} elementsArray - Current elements.
   * @param {number} currentIndex - Current element index.
   * @returns {number} - can be handled element count.
   */
  canHandle(elementsArray, currentIndex) {
    return (elementsArray[currentIndex].tagName === 'VEGA-CODE-BLOCK' &&
      !!elementsArray[currentIndex].querySelector('vega-code-block') === false) ||
      this.isCodeBlockContainer(elementsArray[currentIndex])
      ? 1
      : 0;
  }
  /**
   * Parse to a code block.
   *
   * @param {HTMLElement[]} elementsArray - Current elements.
   * @returns {Nullable<RTECodeBlock>} - Code block.
   */
  handle(elementsArray) {
    const codeBlockElement = this.isCodeBlockContainer(elementsArray[0])
      ? elementsArray[0].querySelector('vega-code-block')
      : elementsArray[0];
    const code = codeBlockElement.querySelector('code');
    if (code) {
      return super.handle([code]); // Call the parent method to handle the code element
    }
    else if (codeBlockElement.hasAttribute('data-content')) {
      // The code element in shadow dom could be empty in firefox.
      // eslint-disable-next-line no-restricted-globals
      const code = document.createElement('code');
      code.textContent = codeBlockElement.dataset.content;
      code.dataset.language = codeBlockElement.dataset.language;
      return super.handle([code]); // Call the parent method to handle the code element
    }
  }
  /* istanbul ignore next */
  /**
   * Append child blocks.
   */
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  appendChildBlocks() { }
  /**
   * Should continue process to child elements.
   *
   * @returns {boolean} - boolean.
   */
  shouldProceedToElementChildren() {
    return false;
  }
  /**
   * Checks if the given element is a code block container.
   *
   * @param {HTMLElement} element - The element to check.
   * @returns {boolean} - Boolean result.
   */
  isCodeBlockContainer(element) {
    return (element.tagName === 'PRE' &&
      element.classList.contains('code-block-container') &&
      element.querySelectorAll('vega-code-block').length === 1);
  }
}
