import * as keycode from '@angular/cdk/keycodes';
import { AfterViewInit, Component, HostListener, inject, Inject, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Globals } from '../../services/globals';
import { BaseEntity } from '../../models/generics/baseentity';
import { BaseEntityWrapper } from '../../models/generics/baseentity.wrapper';
import { BaseEntityListWrapper } from '../../models/generics/baseentitylist.wrapper';
import { MAT_DIALOG_DATA, MatDialogRef, MatFormField } from '../angular-material-index';


@Component({
  selector: 'app-popup-base',
  templateUrl: 'popup-base.component.html',
  styleUrls: ['popup-base.component.scss'],
})

export class PopupBaseComponent implements AfterViewInit {
  @ViewChild('popupForm') detailForm: NgForm;
  @ViewChildren(MatFormField) materialInputFields: QueryList<MatFormField>;

  public description: string;
  public readOnly: boolean = false;

  public keyItemName: string;
  public baseEntityWrapper: BaseEntityWrapper<BaseEntity>;

  protected _focusedItem: BaseEntity;
  public get focusedItem(): BaseEntity {
    return this._focusedItem;
  }
  public set focusedItem(value: BaseEntity) {
    this._focusedItem = value;
  }

  public list: BaseEntityListWrapper<BaseEntity>;

  public data = inject(MAT_DIALOG_DATA);
  public globals = inject(Globals);
  public dialogRef = inject(MatDialogRef<PopupBaseComponent>);
  private lastDetailForm;

  constructor(
  ) {
    this.save = this.save.bind(this);
    this.baseEntityWrapper = this.data.baseEntityWrapper;
    this.keyItemName = this.data.keyItemName;
    this.description = this.data.description;
    this.readOnly = this.data.readOnly;
    this.list = this.data.list;
    this._focusedItem = this.baseEntityWrapper?.entity;
  }

  ngAfterViewInit(): void {
    this.lastDetailForm = this.baseEntityWrapper.detailForm;
    this.baseEntityWrapper.detailForm = this.detailForm;
    // this.baseEntityWrapper.entityWasChanged = false; //!!!, if set false we cannot control that form could be opened already ready to save
    const self = this;
    setTimeout(() => { //to avoid ExpressionChangedAfterItHasBeenCheckedError
      //mark as changed, otherwise required mat-form-field does not get class "mat-form-field-invalid" as should because of required
      self.materialInputFields.forEach(matField => matField._control.ngControl.control.markAsDirty());
      // self.hsInputFields.forEach(hs => hs.markAsDirty());
    }, 0);

  }

  close(result: any) {
    this.baseEntityWrapper.detailForm = this.lastDetailForm;
    this.dialogRef.close(result);
  }

  @HostListener('window:keydown', ['$event'])
  popupKeyboardInput(event: any) {
    if (!this.baseEntityWrapper.keyDownListenerStopped) {
      switch (event.which) {
        case keycode.ESCAPE: // ESC
          event.stopPropagation();
          this.cancel();
          return false;
      }
    }
    return true;
  }

  cancel() {
    this.baseEntityWrapper.cancelWithSave(this.save, () => this.close(false));
  }

  save() {
    this.baseEntityWrapper.save(() => this.close(true));
  }
}
