import { Component, HostListener, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { TranslateService } from '@ngx-translate/core';
import { NotificationService, NotificationType } from '@xdf/commons';

@Component({
  selector: 'byte-additional-param-dialog',
  templateUrl: './additional-param-dialog.component.html',
  styleUrls: ['./additional-param-dialog.component.scss']
})
export class AdditionalParamDialogComponent implements OnInit {

  title: string = "";
  record;
  mode: string = 'view';
  form: FormGroup;
  showCancelButton: boolean;
  constructor(
    public dialogRef: MatDialogRef<AdditionalParamDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    protected translate: TranslateService,
    private notificationService: NotificationService) {
    this.title = this.data.title;
    this.record = this.data.record;
    this.mode = this.data.mode;
    this.showCancelButton = this.data.showCancelButton;
    this.form = new FormGroup({
      additional_parameter: new FormControl({
        value: (this.record && this.record['additional_parameter'] && this.mode !== 'new') ? this.record['additional_parameter'] : '',
        disabled: this.mode === 'view'
      }, Validators.required),
      additional_parameter_value: new FormControl({
        value: (this.record && this.record['additional_parameter_value'] && this.mode !== 'new') ? this.record['additional_parameter_value'] : '',
        disabled: this.mode === 'view'
      }, Validators.required),
    });
  }

  ngOnInit() {
  }

  close() {
    this.dialogRef.close({});
  }

  confirm(event?) {
    if (event) {
      event.preventDefault();
    }
    let recordResult = {};
    if (this.record) {
      recordResult = { ...this.record };
    }
    recordResult['additional_parameter'] = this.form.value['additional_parameter'];
    recordResult['additional_parameter_value'] = this.form.value['additional_parameter_value'];
    if (this.mode === 'new') {
      this.notificationService.showMessage(this.translate.instant('scheduler-task.dialog.create.success'), "", NotificationType.success);
      this.dialogRef.close({ success: true, record: recordResult });
    } else if (this.mode === 'edit') {
      this.notificationService.showMessage(this.translate.instant('scheduler-task.dialog.update.success'), "", NotificationType.success);
      this.dialogRef.close({ success: true, record: recordResult });
    }
     else {
      this.notificationService.showMessage(this.translate.instant('scheduler-task.dialog.delete.success'), "", NotificationType.success);
      this.dialogRef.close({ success: true, record: recordResult });
     }
  }

  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close({ success: false });
  }
}
