import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IVolumeModel } from '@fleio-api/openstack/model/volume.model';
import { IVolumeBackupModel } from '@fleio-api/openstack/model/volume-backup.model';
import { VolumeBackupsApiService } from '@fleio-api/openstack/volume/volume-backups-api.service';
import { map } from 'rxjs/operators';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.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';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-restore-volume-backup-dialog',
  templateUrl: './restore-volume-backup-dialog.component.html',
  styleUrls: ['./restore-volume-backup-dialog.component.scss']
})
export class RestoreVolumeBackupDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') protected formErrors;
  backendErrors = {};
  restoreBackupForm = this.formBuilder.group({
    newVolume: [false],
    volume: ['', Validators.required],
    name: ['', Validators.required],
  });
  dialogTitle = $localize`Restore volume backup ${this.data?.backup?.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Restore backup`,
      primary: true,
      callback: () => this.createOrUpdate(),
    }),
  ];
  dialogForm = this.restoreBackupForm;
  volumeSelectedPlaceholder = $localize`Volume`;
  volumeUnselectedPlaceholder = $localize`Select volume ...`;
  volumesSwitchMapHandler: (search: string) => Observable<any>;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<RestoreVolumeBackupDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      backup: IVolumeBackupModel;
    },
    private volumeBackupsApiService: VolumeBackupsApiService,
    private formBuilder: UntypedFormBuilder,
    private config: ConfigService,
    private notificationService: NotificationService,
  ) {
  }

  changedNewVolume() {
    if (this.restoreBackupForm.controls.newVolume.value) {
      this.restoreBackupForm.controls.volume.disable();
      this.restoreBackupForm.controls.name.enable();
    } else {
      this.restoreBackupForm.controls.volume.enable();
      this.restoreBackupForm.controls.name.disable();
    }
  }

  volumeDisplay(volume?: IVolumeModel): string | undefined {
    if (volume) {
      return volume.name ? `${volume.name} - ${volume.id}` : volume.id.toString();
    } else {
      return undefined;
    }
  }

  ngOnInit() {
    this.changedNewVolume();
    this.volumesSwitchMapHandler = (search) => this.volumeBackupsApiService.getVolumesAvailableForRestoration(
        this.data.backup.id, search ? {search_value: search} : {}
      ).pipe(map(response => response.objects));
  }

  createOrUpdate() {
    if (this.restoreBackupForm.invalid) {
      return;
    }
    this.loading = true;
    const value = this.restoreBackupForm.value;
    let volumeId = null;
    if (value.volume && value.volume.id) {
      volumeId = value.volume.id;
    }

    this.volumeBackupsApiService.restore(this.data.backup.id, volumeId, value.name).subscribe(result => {
      if (result) {
        if (result.operation_id) {
          this.notificationService.showMessageWithLink(
            $localize`Restore volume operation started.`,
            `utilities/operations/${result.operation_id}`,
            $localize`See details`
          );
          this.dialogRef.close('');
        } else {
          this.dialogRef.close($localize`Backup restore scheduled`);
        }
      } else {
        this.dialogRef.close('');
      }
    }, error => {
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }
}
