import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { ITicketModel } from '@fleio-api/plugins/tickets/model/ticket.model';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotificationService } from '@shared/ui-api/notification.service';
import { TicketsApiService } from '@fleio-api/plugins/tickets/tickets-api.service';
import { TicketLinkingApiService } from '@fleio-api/plugins/tickets/ticket-linking-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-remove-ticket-link-dialog',
  templateUrl: './remove-ticket-link-dialog.component.html',
  styleUrls: ['./remove-ticket-link-dialog.component.scss']
})
export class RemoveTicketLinkDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  backendErrors: Record<string, unknown> = {};
  removeTicketLinkingForm: UntypedFormGroup = this.formBuilder.group({
    delete_symmetrical: [false, Validators.required]
  });
  dialogTitle = $localize`Remove ticket linking`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Remove link`,
      primary: true,
      callback: () => this.removeLinking(),
    }),
  ];
  dialogForm = this.removeTicketLinkingForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<RemoveTicketLinkDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      ticket: ITicketModel;
      linkingId: string;
    },
    private notificationService: NotificationService,
    private formBuilder: UntypedFormBuilder,
    private ticketsApiService: TicketsApiService,
    private ticketLinkingApiService: TicketLinkingApiService,
  ) {
  }


  ngOnInit() {
  }

  removeLinking() {
    const value = this.removeTicketLinkingForm.value;
    this.loading = true;
    this.ticketLinkingApiService.removeLinking(this.data.linkingId, value.delete_symmetrical)
      .subscribe(response => {
        this.dialogRef.close(true);
      }, error => {
        this.formErrors.setBackendErrors(error.error.detail);
      }).add(() => {
      this.loading = false;
    });
  }
}
