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';

@Component({
  selector: 'app-create-database-from-backup',
  templateUrl: './create-database-from-backup.component.html',
  styleUrls: ['./create-database-from-backup.component.scss']
})
export class CreateDatabaseFromBackupComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  createDatabaseInstanceFromBackupForm = this.formBuilder.group({
    name: ['', [Validators.required, Validators.max(50)]],
  });
  dialogTitle = $localize`Create database instance from backup ${this.data.backup.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Create instance`,
      primary: true,
      callback: () => this.createDatabaseInstance(),
    }),
  ];
  dialogForm = this.createDatabaseInstanceFromBackupForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<CreateDatabaseFromBackupComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      database_instance: IDbaasInstanceModel;
      backup: {
        name: string;
        id: string;
      };
    },
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  public createDatabaseInstance() {
    if (this.createDatabaseInstanceFromBackupForm.invalid) {
      return;
    }
    this.loading = true;
    this.dbaasInstancesApiService.createDatabaseInstanceFromBackup(
      this.data.database_instance.id, this.createDatabaseInstanceFromBackupForm.controls.name.value,
      this.data.backup,
    ).subscribe({
      next: () => {
        this.loading = false;
        this.dialogRef.close(true);
      }, error: (error) => {
        this.formErrors.setBackendErrors(error.error);
        this.loading = false;
      }
    });
  }

  ngOnInit() {
  }

}
