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 { IIcon } from '@shared/ui/common/interfaces/icon';
import { NotificationService } from '@shared/ui-api/notification.service';

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

  public incrementalInfo: IIcon = {
    name: 'info',
    verticalAlign: 'middle',
    fontSize: '20px',
    marginLeft: '5px',
    marginTop: '2px',
    tooltip: $localize`Create an incremental backup based on the last full backup.`
  };

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

  public createBackup() {
    if (this.createDatabaseBackupForm.invalid) {
      return;
    }
    this.loading = true;
    this.dbaasInstancesApiService.createBackup(
      this.data.database_instance.id,
      this.createDatabaseBackupForm.controls.name.value,
      this.createDatabaseBackupForm.controls.swift_container.value,
      this.createDatabaseBackupForm.controls.incremental.value,
    ).subscribe({
      next: () => {
        this.loading = false;
        this.notificationService.showMessage($localize`Backup creation scheduled.`);
        this.dialogRef.close(true);
      }, error: (error) => {
        this.formErrors.setBackendErrors(error.error);
        this.loading = false;
      }
    });
  }

  ngOnInit() {
  }

}
