import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { InvoicesApiService } from '@fleio-api/billing/invoices/invoices-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IInvoiceModel } from '@fleio-api/billing/model/invoice.model';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';

@Component({
  selector: 'app-invoice-delete-dialog',
  templateUrl: './invoice-delete-dialog.component.html',
  styleUrls: ['./invoice-delete-dialog.component.scss']
})
export class InvoiceDeleteDialogComponent implements IBaseDialog, OnInit {
  invoice: IInvoiceModel;
  allowDelete: boolean;
  dialogTitle = $localize`Delete invoice?`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Delete`,
      primary: true,
      callback: () => this.delete(),
    }),
  ];
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<InvoiceDeleteDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      invoiceID: FleioId;
    },
    private invoicesApiService: InvoicesApiService,
    private notificationService: NotificationService,
  ) {
  }

  ngOnInit() {
    if (this.data && this.data.invoiceID) {
      this.loading = true;
      this.invoicesApiService.get(this.data.invoiceID).subscribe(response => {
        this.invoice = response;
        this.allowDelete = !(this.invoice && this.invoice.transactions && Array.isArray(this.invoice.transactions) &&
          this.invoice.transactions.length > 0);
        this.dialogActions[0].disabled = !this.allowDelete;
        this.loading = false;
      });
    }
  }

  delete() {
    this.loading = true;
    this.invoicesApiService.delete(this.invoice.id).subscribe(response => {
      this.dialogRef.close(true);
    }, error => {
      this.notificationService.showMessage($localize`Failed to delete invoice.`);
      this.dialogRef.close(false);
    }).add(() => {
      this.loading = false;
    });
  }
}
