import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { AuthService } from '@shared/auth/auth.service';
import { ConfigService } from '@shared/config/config.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';

@Component({
  selector: 'app-instance-details-create-snapshot-dialog',
  templateUrl: './instance-details-create-snapshot-dialog.component.html',
  styleUrls: ['./instance-details-create-snapshot-dialog.component.scss']
})
export class InstanceDetailsCreateSnapshotDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  loading = false;
  createSnapshotForm: UntypedFormGroup = new UntypedFormGroup({
    name: new UntypedFormControl('', Validators.required),
    create_snapshot_as_client: new UntypedFormControl(false, Validators.required)
  });
  dialogTitle = $localize`Create snapshot for instance ${this.data.instanceName || this.data.instanceId}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Create`,
      primary: true,
      callback: () => this.createSnapshot(),
    }),
  ];
  dialogForm = this.createSnapshotForm;
  adminProjectTooltip = $localize`End-user will NOT see this snapshot\nand NO storage cost will incur`;
  clientProjectTooltip = $localize`End-user will see this snapshot\nand storage cost will incur\n
  (assuming you have a\nmatching Image pricing rule)`;
  estimatedCost = null;
  estimatedCostLoading = false;

  constructor(
    public auth: AuthService,
    public config: ConfigService,
    private notificationService: NotificationService,
    private instancesApiService: InstancesApiService,
    public dialogRef: MatDialogRef<InstanceDetailsCreateSnapshotDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      instanceId: string;
      instanceName: string;
    },
  ) {
  }

  ngOnInit() {
    if (!this.auth.feature('ui.openstack.instances.create_snapshot_dialog.project_select')) {
      this.createSnapshotForm.removeControl('create_snapshot_as_client');
      this.getPrice();
    } else {
      this.createSnapshotForm.valueChanges.subscribe(() => {
        if (this.createSnapshotForm.controls.create_snapshot_as_client.value) {
          this.getPrice();
        } else {
          this.estimatedCost = null;
        }
      });
    }
  }

  getPrice() {
    if (this.auth.feature('openstack.instances.snapshots.pricing')) {
      this.estimatedCostLoading = true;
      this.instancesApiService.getSnapshotPricePerCycle(this.data.instanceId).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;
      });
    }
  }

  createSnapshot() {
    this.loading = true;
    const value = this.createSnapshotForm.value;
    if (!this.createSnapshotForm.valid) {
      this.loading = false;
      return;
    }
    this.instancesApiService.createSnapshot(this.data.instanceId, value).pipe().subscribe(() => {
      this.loading = false;
      this.dialogRef.close(true);
    }, error => {
      this.loading = false;
      this.notificationService.showMessage($localize`Failed to create snapshot`);
      this.formErrors.setBackendErrors(error.error);
    });
  }

}
