import { Component, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { TicketsSignaturesApiService } from '@fleio-api/plugins/tickets/tickets-signatures-api.service';
import { TicketDepartmentsApiService } from '@fleio-api/plugins/tickets/ticket-departments-api.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';

@Component({
  selector: 'app-add-signature-dialog',
  templateUrl: './add-signature-dialog.component.html',
  styleUrls: ['./add-signature-dialog.component.scss']
})
export class AddSignatureDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  addSignatureForm = this.formBuilder.group({
    department: [null],
    content: ['']
  });
  dialogTitle = $localize`Add signature`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Submit`,
      primary: true,
      callback: () => this.addSignature(),
    }),
  ];
  dialogForm = this.addSignatureForm;
  loading = false;
  backendErrors = {};
  departmentSelectedPlaceholder = $localize`Department`;
  departmentUnselectedPlaceholder = $localize`Select department ...`;

  constructor(
    public dialogRef: MatDialogRef<AddSignatureDialogComponent>,
    private formBuilder: UntypedFormBuilder,
    private ticketsSignaturesApiService: TicketsSignaturesApiService,
    public ticketDepartmentsApiService: TicketDepartmentsApiService,
  ) { }

  public addSignature() {
    if (!this.addSignatureForm.valid) {
      return;
    }
    const data = this.addSignatureForm.value;
    if (data.department) {
      data.department = data.department.id;
    }
    this.loading = true;
    this.ticketsSignaturesApiService.create(
        data
      ).subscribe(result => {
      this.dialogRef.close(true);
    }, error => {
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit(): void {
  }

}
