import { IPageElement, PageElement } from './page-element';
import { PageElementMatIcon } from './page-element-mat-icon';
import { PageElementTableRow } from './page-element-table-row';

export interface IPageElementTableHeader extends IPageElement {
  thTdsTexts?: Array<string>;

  tableId: string;

  actionsMenuButton?: PageElementMatIcon;
  actions?: Array<string>;

  updateDeleteControl?: boolean;
}

export class PageElementTableHeader extends PageElement {

  thTd: 'th' | 'td' = 'th';
  thTdsTexts?: Array<string>;

  tableId: string;

  _actionsMenuButton?: PageElementMatIcon;
  actions?: Array<string>;

  updateDeleteControl?: boolean;

  constructor(ipe: IPageElementTableHeader) {
    super(ipe);
    this.tableId = ipe.tableId;
    this.actions = ipe.actions ? [...ipe.actions]: [];
    this._actionsMenuButton = ipe.actionsMenuButton;
    if (!(this instanceof PageElementTableRow)) {
      this.thTdsText = ipe.thTdsTexts ? [...ipe.thTdsTexts]: [];
    }
  }

  override get pageElement(): Cypress.Chainable {
    return this.pageElement || cy.get(this.tableId + this.id);
  }

  set thTdsText(texts: Array<string>) {
    this.thTdsTexts = texts;
  }

  get thTdsText() {
    return this.thTdsTexts || [];
  }

  override validateDefaultFieldValues(): void {
    // TODO investigar
    //  super.validateDefaultFieldValues();

     // VALIDATE THS TEXT
     if (this.thTdsTexts) {
      cy.get(this.id + ' > ' + this.thTd).each((td, index) =>
        cy.wrap(td).invoke('text').should('contain', this.thTdsTexts![index]));
     }

     // VALIDATE ITEM MENU
     if (this.actions || this.updateDeleteControl) {
       this.validateActionsMenuAndOptions();
     }
  }

  validateActionsMenuAndOptions() {
    if (this._actionsMenuButton) {
      this.actionsMenuButton?.validateDefaultFieldValues();
      this.actionsMenuButton?.click();
      this.validateActionsOptions();
    }
  }

  get actionsMenuButton() {
    this._actionsMenuButton?.pageElement.scrollIntoView();
    return this._actionsMenuButton;
  }

  validateActionsOptions() {
    cy.get('button.mat-mdc-menu-item').each((btn, index) => cy.wrap(btn).invoke('text').should('include', this.actions![index]))
  }

  clickCheck(): void {
    //  new PageElementMatCheckBox(this.iPageElement.item1Marcar).focusClick();
  }

  buttonCheckUnchekAllClick() {
    this.actionsMenuButton!.click();
    cy.get('button.mat-mdc-menu-item:nth-child(1)').click();
  }

  buttonDeleteAllClick() {
    this.actionsMenuButton!.click();
    cy.get('button.mat-mdc-menu-item:nth-child(2)').click();
  }
}
