import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { ConfigService } from '@shared/config/config.service';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.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';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-create-os-backup-dialog',
  templateUrl: './create-os-backup-dialog.component.html',
  styleUrls: ['./create-os-backup-dialog.component.scss']
})
export class CreateOsBackupDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  loading = false;
  backupForm = this.formBuilder.group({
    backup_type: ['manual'],
    create_as_client: [false],
    rotation: [this.data.existingBackupsCount + 1, [ValidatorsHelper.requiredIntegerValidator, Validators.min(1)]],
    backup_name: ['', Validators.required],
  });
  dialogTitle = $localize`Create backup for instance ${this.data.instance.name || this.data.instance.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Create backup`,
      primary: true,
      callback: () => this.createBackup(),
    }),
  ];
  dialogForm = this.backupForm;
  isStaff = false;
  fieldRequiredTxt = $localize`This field is required!`;

  rotationControl = this.backupForm.controls.rotation;
  createAsClientControl = this.backupForm.controls.create_as_client;
  estimatedCost = null;
  estimatedCostLoading = false;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
    private instancesApiService: InstancesApiService,
    public config: ConfigService,
    public dialogRef: MatDialogRef<CreateOsBackupDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      instance: IInstanceModel;
      existingBackupsCount: number;
      existingBackupsCountClientProject: number;
    },
  ) { }

  getPrice() {
    if (this.config.authService.feature('openstack.osbackup.pricing')) {
      this.estimatedCostLoading = true;
      this.instancesApiService.getBackupPrice(this.data.instance.id).subscribe({
        next: value => {
          this.estimatedCost = value.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;
      });
    }
  }

  public createBackup() {
    this.loading = true;
    if (!this.backupForm.valid) {
      this.loading = false;
      return;
    }
    const value = this.backupForm.value;
    this.instancesApiService.createBackup(this.data.instance.id, value).subscribe(response => {
      this.loading = false;
      this.dialogRef.close(true);
    }, error => {
      this.loading = false;
      this.formErrors.setBackendErrors(error.error);
    });
  }

  ngOnInit(): void {
    if (this.config.currentConfigurationName === 'staff') {
      this.isStaff = true;
      this.createAsClientControl.enable();
      this.backupForm.valueChanges.subscribe(() => {
        if (this.createAsClientControl.value) {
          this.getPrice();
        } else {
          this.estimatedCost = null;
        }
      });
    } else {
      this.createAsClientControl.disable();
      this.getPrice();
    }
  }

}
