import { isHTMLElement } from '../../../../../../utils/ui';
import { ElementToTextNodeStrategy } from './element-to-text-node-strategy';
import htmlElementToAnnotationGenerator from './annotation-handler/html-element-to-annotation-generator';
import { RTETextNode } from '../../../../dto/nodes/text-node';
import { cleanObject } from '../../../../../../utils/object';
/**
 * Class to handle inline html element to text node dto
 */
export class InlineElementToTextNodeStrategy extends ElementToTextNodeStrategy {
  /**
   * @inheritDoc
   */
  canHandle(elementsArray, currentIndex) {
    const element = elementsArray[currentIndex];
    return isHTMLElement(element) && (element.nodeName === 'BR' || element.childNodes.length === 0)
      ? 1
      : 0;
  }
  /**
   * @inheritDoc
   */
  handle(elementsArray, options, annotations) {
    const disableAutoMatchFormat = !!(options && options.autoMatchFormat === false);
    const parentAnnotations = Object.assign({}, annotations);
    const child = elementsArray[0];
    const curAnnotations = htmlElementToAnnotationGenerator.generate(RTETextNode, child, Object.assign({ parentAnnotations: disableAutoMatchFormat
        ? {
          inlineHtml: parentAnnotations.inlineHtml,
          link: parentAnnotations.link,
          code: parentAnnotations.code,
        }
        : annotations }, options));
    if (child.nodeName === 'BR') {
      return this.generateTextNode('\n', curAnnotations);
    }
    else if (child.childNodes.length === 0) {
      // For empty dom, there will be no internal iteration, we need to handle it directly here.
      // Example: <span></span>, <video src='...'></video>
      const emptyNodeAnnotations = disableAutoMatchFormat
        ? cleanObject(Object.assign(Object.assign({}, (RTETextNode.supportsHtmlTag(child.nodeName.toLowerCase()) ? curAnnotations : {})), { inlineHtml: curAnnotations.inlineHtml }))
        : curAnnotations;
      return Object.assign({}, this.generateTextNode('', emptyNodeAnnotations));
    }
  }
}
