import * as keycode from '@angular/cdk/keycodes';
import { AfterViewInit, Component, HostListener, Inject, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import * as Cnst from '../../consts';
import { Globals, IMessageBoxButton, IMessageBoxData } from '../../services/globals';
import { HenselTranslateService } from '../../services/localization/hensel-translate.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '../angular-material-index';

const enum EN_MessageBoxInterfaceType {
  old = '',
  new = 'new-'
}

@Component({
  // tslint:disable-next-line: component-selector
  selector: 'hr-message-box',
  templateUrl: 'message-box.component.html',
  styleUrls: ['message-box.component.scss'],
})

export class MessageBoxComponent implements AfterViewInit {
  @ViewChild('popupForm') detailForm: NgForm;

  public description: string;
  public readOnly: boolean = false;
  public messageBoxInterfaceType: EN_MessageBoxInterfaceType = EN_MessageBoxInterfaceType.new;

  public overHeader: string;
  public header: string;
  public message: string;
  public buttons: IMessageBoxButton[];
  public cancelButtonIdx: number;
  public defaultButtonIdx: number;
  public messageType: Cnst.EN_LogType;

  constructor(
    public dialogRef: MatDialogRef<MessageBoxComponent>,
    public translate: HenselTranslateService,
    public globals: Globals,
    @Inject(MAT_DIALOG_DATA) data: IMessageBoxData
  ) {
    this.overHeader = this.translate.translateString(data.overHeader);
    this.header = this.translate.translateString(data.header);
    this.message = this.translate.translateString(data.message);
    this.buttons = data.buttons;
    this.messageType = data.type;
    if (this.buttons.length === 1) {
      this.buttons[0].default = true;
      this.buttons[0].cancel = true;
    }
    this.buttons.forEach((btn: IMessageBoxButton, index: number) => {
      if (btn.default) this.defaultButtonIdx = index;
      if (btn.cancel) this.cancelButtonIdx = index;
      if (!btn.code) btn.code = 0;
    });
  }

  ngAfterViewInit(): void {
    setTimeout(() => document.getElementById('btn' + (this.defaultButtonIdx + 1))?.focus());
  }

  close(code: number) {
    this.dialogRef.close(code);
  }

  btnClick(btn: IMessageBoxButton) {
    this.close(btn?.code || 0);
  }


  @HostListener('window:keydown', ['$event'])
  popupKeyboardInput(event: any) {
    switch (event.which) {
      case keycode.ESCAPE:
        event.stopPropagation();
        this.btnClick(this.buttons[this.cancelButtonIdx]);
        return false;
      case keycode.ENTER:
        event.stopPropagation();
        this.btnClick(this.buttons[this.defaultButtonIdx]);
        return false;
    }
    return true;
  }
}
