import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-add-database-replica-dialog',
  templateUrl: './add-database-replica-dialog.component.html',
  styleUrls: ['./add-database-replica-dialog.component.scss']
})
export class AddDatabaseReplicaDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  createDatabaseReplicaForm = this.formBuilder.group({
    name: ['', [Validators.required, Validators.max(50)]],
  });
  dialogTitle = $localize`Create replica for ${this.data.database_instance.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Create replica`,
      primary: true,
      callback: () => this.createReplica(),
    }),
  ];
  dialogForm = this.createDatabaseReplicaForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<AddDatabaseReplicaDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { database_instance: IDbaasInstanceModel },
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
  ) {
  }

  public createReplica() {
    if (this.createDatabaseReplicaForm.invalid) {
      return;
    }
    this.loading = true;
    this.dbaasInstancesApiService.createDatabaseReplica(
      this.data.database_instance.id, this.createDatabaseReplicaForm.controls.name.value,
    ).subscribe({
      next: (response) => {
        this.loading = false;
        if (response.operation_id) {
          this.notificationService.showMessageWithLink(
            $localize`Create database instance replica operation started.`,
            `utilities/operations/${response.operation_id}`,
            $localize`See details`
          );
        }
        this.dialogRef.close(true);
      }, error: (error) => {
        this.formErrors.setBackendErrors(error.error);
        this.loading = false;
      }
    });
  }

  ngOnInit() {
  }

}
