import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IFlavorModel } from '@fleio-api/openstack/model/flavor.model';
import { FlavorsApiService } from '@fleio-api/openstack/flavor/flavors-api.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';
import { OpenstackUtils } from '@fleio-api/openstack/openstack-utils';

@Component({
  selector: 'app-flavor-details-overview',
  templateUrl: './flavor-details-overview.component.html',
  styleUrls: ['./flavor-details-overview.component.scss']
})
export class FlavorDetailsOverviewComponent extends DetailsComponentBase<IFlavorModel> implements OnInit {
  ramDisplay: string;
  swapDisplay: string;
  properties: object;

  constructor(
    private flavorsApi: FlavorsApiService, private refreshService: RefreshService,
    private notificationService: NotificationService,
    public config: ConfigService,
  ) {
    super();
  }

  ngOnInit(refreshTimerInterval?: number) {
    super.ngOnInit(refreshTimerInterval);
    this.ramDisplay = OpenstackUtils.MiBToUserFriendly(this.object.memory_mb, true);
    this.swapDisplay = OpenstackUtils.MiBToUserFriendly(this.object.swap, true);
    this.properties = this.object?.properties ? JSON.parse(this.object.properties) : {};
  }

  updateFlavor() {
    const data = {
      id: this.object.id,
      out_of_stock: this.object.out_of_stock,
      show_for_end_user: this.object.show_for_end_user,
      use_for_dbaas: this.object.use_for_dbaas,
    };
    this.flavorsApi.partialUpdate(this.object.id, data).subscribe(
      () => {
        this.refreshService.refresh();
      }, (error) => {
        this.notificationService.showMessage(error?.error?.detail || $localize`Failed to update flavor`);
        this.refreshService.refresh();
      }
    );
  }

  showToggles() {
    return this.object;
  }

  protected readonly Object = Object;
}
