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 { debounceTime } from 'rxjs/operators';
import { VolumesApiService } from '@fleio-api/openstack/volume/volumes-api.service';
import { AuthService } from '@shared/auth/auth.service';
import { ConfigService } from '@shared/config/config.service';
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-edit-volume-backup-dialog',
  templateUrl: './edit-volume-backup-dialog.component.html',
  styleUrls: ['./edit-volume-backup-dialog.component.scss']
})
export class EditVolumeBackupDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') protected formErrors;
  backendErrors = {};
  backupForm = this.formBuilder.group({
    for_client: [false],
    name: ['', Validators.required],
    incremental: [false],
    force: [false],
    description: [''],
    volume: ['', Validators.required],
  });
  dialogTitle = null;
  dialogActions: Array<IAction> = [];
  dialogForm = this.backupForm;
  showVolumeSelect: boolean;
  loading = false;
  fieldRequiredTxt = $localize`This field is required!`;
  updateBackupTxt = $localize`Update backup`;
  createBackupTxt = $localize`Create backup`;
  volumeSelectedPlaceholder = $localize`Volume`;
  volumeUnselectedPlaceholder = $localize`Select volume ...`;
  estimatedCost: string;
  estimatedCostLoading = false;

  constructor(
    public dialogRef: MatDialogRef<EditVolumeBackupDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      volume: IVolumeModel;
      backup: IVolumeBackupModel;
    },
    private volumeBackupsApiService: VolumeBackupsApiService,
    private formBuilder: UntypedFormBuilder,
    public auth: AuthService,
    public config: ConfigService,
    public volumesApiService: VolumesApiService,
  ) {
  }

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


  ngOnInit() {
    if (this.data.backup) {
      this.dialogTitle = $localize`Edit volume backup ${this.data.backup.name}`;
      this.dialogActions.push(
        new DialogCallbackAction({
          name: this.updateBackupTxt,
          primary: true,
          callback: () => this.createOrUpdate(),
        }),
      );
      this.backupForm.patchValue(this.data.backup);
      this.backupForm.controls.for_client.disable();
      this.backupForm.controls.incremental.disable();
      this.backupForm.controls.force.disable();
    } else {
      if (this.data.volume) {
        this.dialogTitle = $localize`Backup volume ${this.data.volume.name || this.data.volume.id}`;
      } else {
        this.dialogTitle = $localize`Create volume backup`;
      }
      this.dialogActions.push(
        new DialogCallbackAction({
          name: this.createBackupTxt,
          primary: true,
          callback: () => this.createOrUpdate(),
        }),
      );
    }

    this.backupForm.valueChanges.pipe(debounceTime(300)).subscribe(() => {
      this.getSimulatedPrice();
    });

    this.showVolumeSelect = !this.data.backup && !this.data.volume;

    if (!this.showVolumeSelect) {
      this.backupForm.controls.volume.disable();
    }
  }

  createOrUpdate() {
    const value = this.backupForm.value;
    let volume = this.data.volume;

    if (this.showVolumeSelect) {
      volume = value.volume;
    }

    if (volume) {
      value.volume_id = volume.id ? volume.id: volume;
    }

    let request;

    if (this.data.backup) {
      value.id = this.data.backup.id;
      request = this.volumeBackupsApiService.update(value.id, value);
    } else {
      request = this.volumeBackupsApiService.create(value);
    }
    this.loading = true;
    request.subscribe(result => {
      if (result) {
        this.dialogRef.close('Ok');
      } else {
        this.dialogRef.close('');
      }
    }, error => {
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }

  getSimulatedPrice() {
    if (this.auth.feature('openstack.volumes.backups.show-price-on-create')) {
      const volume = this.backupForm.controls.volume.value || this.data.volume;
      if (volume && typeof volume.size === 'number' && volume.region &&
        ((this.backupForm.controls.for_client.value && volume.client) ||
          !this.auth.feature('ui.openstack.volumes.backups.show-project-checkbox'))) {
        const params = {
          volume_size: volume.size,
          region: volume.region,
        } as any;
        if (volume.client?.id) {
          params.client_id = volume.client?.id;
        }
        this.estimatedCostLoading = true;
        this.volumeBackupsApiService.getPrice(params).subscribe({
          next: response => {
            this.estimatedCost = response.estimated_cost_display;
          },
          error: error => {
            if (error?.error?.detail) {
              if (this.config.authService.feature('ui.staff')) {
                this.estimatedCost = error.error.detail;
              } else {
                this.estimatedCost = null;
              }
            }
          }
        }).add(() => {
          this.estimatedCostLoading = false;
        });
      } else {
        this.estimatedCost = null;
      }
    }
  }

}
