// File: PageObjectType.ts
// Author: Vinicius Martins Ferraz
// Date: 30/09/2019
import { PageElementSnackbar } from '../page-element/page-element-snack-bar';
import { defaultUpdateEntityPageStructure } from './default-update-entity-page-structure';
import { PageElementButton } from '../page-element/page-element-button';
import { PageElementAny } from '../page-element/page-element-any';
import { BasicStruct } from './i-page-structure';

export const TODAY = ('0' + new Date().getDate()).slice(-2) + '/' + ('0' + (new Date().getMonth() + 1)).slice(-2) + '/' + new Date().getFullYear();
export const HOUR = ('0' + new Date().getHours()).slice(-2) + ':' + ('0' + new Date().getMinutes()).slice(-2);
export const NOW = TODAY + ' - ' + HOUR;

export const format = {
  toBackendDate: (d?: Date) => d? `${d.getFullYear()}-${(""+(d.getUTCMonth()+1)).padStart(2, '0')}-${(''+d.getUTCDate()).padStart(2, '0')}` : '',
  toPtBrDate: (d?: Date) => d? `${('' + d.getUTCDate()).padStart(2, '0')}/${(""+(d.getUTCMonth()+1)).padStart(2, '0')}/${d.getFullYear()}` : '',
}

export enum StringCompareStrategy {
  match = 'match',
  include = 'include'
}

export abstract class PageObject {

  menuButton: PageElementButton;

  protected urlCompareStrategy: StringCompareStrategy = StringCompareStrategy.include;

  constructor(protected struct: BasicStruct, protected title: string, protected url?: string) {
    this.menuButton = new PageElementButton({id: `#main-menu-${title}-id`});
  }

  visit(urlParam: string = ''): void {
    if (this.url && typeof this.url === 'string') cy.visit('/' + this.url + (this.url.endsWith('/') ? '' : '/') + urlParam);
    else  cy.visit('/');
  }

  public visitByMainMenu() {
    this.menuButton.click();
  }

  validateDeletionSuccess() {
    defaultUpdateEntityPageStructure.snackBarDeletionSuccess().validateDefaultFieldValues();
  }

  public validatePage(): void {
    this.validatePageTitleAndUrl();
    this.validatePageStructure();
  }

  protected validatePageStructure() {
    this.struct.elements?.forEach(element => {
      if (element instanceof PageElementSnackbar) {
        return;
      }

      if(element.validateDefaultFieldValues) element.validateDefaultFieldValues();
    });
  }

  protected  validatePageTitleAndUrl(): void {
    this.validateUrl();
    this.validateTitle();
  }

  protected validateTitle(title: string = this.title) {
    new PageElementAny({
      id: 'mat-card-title.page-title span'
    }).pageElement.invoke('text').should('include', title);
  }

  protected validateUrl(url: string | RegExp | undefined = this.url, urlCompareStrategy: StringCompareStrategy = this.urlCompareStrategy) {
    if (url) cy.url().should(urlCompareStrategy, url);
  }

  public  closeSnackBar(): void {
    cy.get('div[matsnackbaractions] button').click();
  }

}


