import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IFlavorModel } from '@fleio-api/openstack/model/flavor.model';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { of } from 'rxjs';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';

@Component({
  selector: 'app-instance-resize-form',
  templateUrl: './instance-resize-form.component.html',
  styleUrls: ['./instance-resize-form.component.scss']
})
export class InstanceResizeFormComponent extends DetailsFormBase<IInstanceModel> implements OnInit {
  @ViewChild('flavorsAsCards') flavorsAsCards;
  flavors: IFlavorModel[];
  selectedFlavor: IFlavorModel | null;
  flavorIncompatibility = false;
  estimatedCost: string;
  estimatedCostLoading: boolean;

  constructor(private activatedRoute: ActivatedRoute, private router: Router, public config: ConfigService,
              private notificationService: NotificationService, private instancesApi: InstancesApiService) {
    super();
  }

  private resizeInstance() {
    this.selectedFlavor = this.flavorsAsCards.selectedFlavor;
    if (!this.selectedFlavor) {
      this.notificationService.showMessage($localize`Select a flavor`);
      return of(null);
    }
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Resize instance?`,
      message: '',
      importantMessage: $localize`Instance resize will cause downtime. The instance will shutdown and the disk image will be copied to a new disk. This may take a while, depending on the disk size.`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.objectController.loading = true;
        this.instancesApi.resize(this.object.id, this.selectedFlavor.id).pipe().subscribe(() => {
          this.notificationService.showMessage($localize`Resize instance started`);
          this.router.navigateByUrl(
            this.config.getPanelUrl(`openstack/instances/${this.object.id}`)
          ).catch(() => {
          });
        }, error => {
          this.objectController.loading = false;
          this.notificationService.showMessage(error.error.detail);
        });
      }
    });
    return of(null);
  }

  onFlavorChosen(flavor: IFlavorModel) {
    // on flavors as cards flavor select
    if (this.config.authService.feature('openstack.instances.resize.show-price')) {
      const clientId = this.object?.client?.id;
      if (clientId) {
        const networkIds = [];
        if (this.object.net_details?.ports) {
          this.object.net_details.ports.forEach(port => {
            if (!networkIds.includes(port.network)) {
              networkIds.push(port.network);
            }
          });
        }
        const params = {
          client_id: clientId,
          region: this.object.region,
          flavor_id: flavor.id,
          network_ids: networkIds.length ? networkIds : null,
        } as any;
        if (this.object?.availability_zone) {
          params.availability_zone = this.object.availability_zone;
        }
        if (this.object?.image?.id) {
          params.image_id = this.object.image.id;
        }
        this.estimatedCostLoading = true;
        this.instancesApi.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;
        });
      }
    }
  }

  ngOnInit() {
    if (this.objectController) {
      this.objectController.actionCallback = () => this.resizeInstance();
    }
    this.selectedFlavor = null;
    if (this.activatedRoute && this.activatedRoute.snapshot && this.activatedRoute.snapshot.data &&
      this.activatedRoute.snapshot.data.resizeOptions) {
      this.flavors = this.activatedRoute.snapshot.data.resizeOptions.flavors;
    }
  }

}
