import { LisioComponent } from "@lisio/lisio-engine";
import { TranslationController } from "../../../controllers/translation/translation-controller";
import { translateEvent } from "../../../../misc/events";

/**
 * Abstract class extending LisioComponent to manage the dynamic translation of an aria-label attribute.\
 */
abstract class LisioAriaLabelComponent extends LisioComponent {
  /**
   * Public method to change aria-label attribute
   * @param {string} textId - Id of new aria-label text
   * @param {boolean} noTranslate - Indicates if text has to be translated. Default value set to false
   * @returns Returns nothing
   * @source
   */
  public changeAriaLabel(
    ariaLabelTextId: string,
    noTranslate: boolean = false,
  ): void {
    if (noTranslate) {
      if (this._htmlElement == undefined) {
        this._attributes.set("aria-label", ariaLabelTextId);
      } else {
        this._htmlElement.setAttribute("aria-label", ariaLabelTextId);
      }
    } else {
      if (this._htmlElement == undefined) {
        this._attributes.set(
          "aria-label",
          TranslationController.current.getTranslation(ariaLabelTextId),
        );
      } else {
        this._htmlElement.setAttribute(
          "aria-label",
          TranslationController.current.getTranslation(ariaLabelTextId),
        );
      }
    }
  }

  /**
   * Constructor of abstract class {@link LisioAriaLabelComponent | LisioAriaLabelComponent}
   * @param {string} componentName - Component name
   * @param {string | undefined} ariaLabelTextId - Id of text to write in aria-label component's attribute
   * @param {string | undefined} id - Id of component
   * @param {string[] | undefined} cssClasses - CSS classes of component
   * @param {Map<string, string> | undefined} attributes - Component attributes
   * @param {boolean | undefined} noTranslate - Indicates if text has to be translated
   * @source
   */
  constructor(
    componentName: string,
    ariaLabelTextId?: string,
    id?: string,
    cssClasses?: string[],
    attributes?: Map<string, string>,
    noTranslate?: boolean,
  ) {
    let ariaLabelText;
    if (ariaLabelTextId) {
      if (noTranslate) {
        ariaLabelText = ariaLabelTextId;
      } else {
        try {
          ariaLabelText =
            TranslationController.current.getTranslation(ariaLabelTextId);
        } catch (error) {
          console.log(error);
          ariaLabelText = undefined;
        }
      }
    }
    if (ariaLabelText) {
      attributes?.set("aria-label", ariaLabelText);
    }
    if (ariaLabelTextId && !noTranslate) {
      window.addEventListener(translateEvent.type, () => {
        this.changeAriaLabel(ariaLabelTextId);
      });
    }
    super(componentName, id, cssClasses, attributes);
  }
}

export { LisioAriaLabelComponent };
