import { AnnotationGeneratorStrategyAbstract } from './annotation-generator-strategy.abstract';
/** Handle custom attribute annotation */
export class CustomAttributeAnnotationHandler extends AnnotationGeneratorStrategyAbstract {
  /**
   * Can be handle.
   *
   * @param {RTEDtoClassPrototype} targetDto - Target DTO.
   * @param {HtmlElementToAnnotationGenerateOptions} [options] - Options for annotation generator.
   * @returns {boolean} - .
   */
  canHandle(targetDto, options) {
    return !options.skipCustomAnnotations && !!targetDto;
  }
  /**
   * Handle annotation.
   *
   * @param {HTMLElement} element - Current elements.
   * @returns {VegaRTETextAnnotations} - Annotation.
   */
  handle(element) {
    const attributes = this.getAttributes(element);
    return Object.keys(attributes).length > 0 ? { customAttribute: attributes } : {};
  }
  /**
   * Obtain the custom attributes of element, excluding 'style' and 'class'.
   *
   * @param {HTMLElement} element - current element.
   * @returns {Record<string, string>} - Record<string, string>.
   */
  getAttributes(element) {
    const attributeNames = element
      .getAttributeNames()
      .filter((attr) => attr !== 'style' && attr !== 'class' && this.isValidAttr(attr));
    return attributeNames.reduce((acc, item) => {
      acc[item] = element.getAttribute(item);
      return acc;
    }, {});
  }
  /**
   * Check if the attribute name is valid.
   *
   * @param {string} attr - Attribute name.
   * @returns {boolean} - True if valid, false otherwise.
   */
  isValidAttr(attr) {
    return /^[a-zA-Z_][\w-]*$/.test(attr);
  }
}
