import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { ConfigService } from '@shared/config/config.service';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { PublicKeysApiService } from '@fleio-api/public-key/public-key-api.service';
import { VolumesApiService } from '@fleio-api/openstack/volume/volumes-api.service';
import { NetworksApiService } from '@fleio-api/openstack/network/networks-api.service';
import { RoutersApiService } from '@fleio-api/openstack/routers/routers-api.service';
import { ImagesApiService } from '@fleio-api/openstack/image/image-api.service';
import { PortsApiService } from '@fleio-api/openstack/port/ports-api.service';
import { FleioApiService } from '@fleio-api/fleio-api.service';
import {
  OpenstackBillingServicesApiService
} from '@fleio-api/openstack/billing/services/openstack-billing-services-api.service';
import { IServiceModel } from '@fleio-api/billing/model/service.model';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';

@Component({
  selector: 'app-client-details-cloud-resources',
  templateUrl: './client-details-cloud-resources.component.html',
  styleUrls: ['./client-details-cloud-resources.component.scss']
})
export class ClientDetailsCloudResourcesComponent extends DetailsComponentBase<IClientModel> implements OnInit {
  cloudSummary: {
    [key: string]: {
      name: string;
      objects: Array<Record<any, any>>;
      count: number;
      load_count: number;
    };
  };
  service: IServiceModel = null;
  cloudSummaryKeys: Array<string> = [];
  clientOsProjectId: FleioId;
  disabledShowMoreButton = {};
  loading = false;

  constructor(
    private clientsApiService: ClientsApiService,
    private openstackBillingServicesApiService: OpenstackBillingServicesApiService,
    private instancesApiService: InstancesApiService,
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private publicKeysApiService: PublicKeysApiService,
    private volumesApiService: VolumesApiService,
    private networksApiService: NetworksApiService,
    private routersApiService: RoutersApiService,
    private imagesApiService: ImagesApiService,
    private portsApiService: PortsApiService,
    public config: ConfigService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  ngOnInit() {
    super.ngOnInit();
  }

  showAll(resourceType: string) {
    let filteringField = 'project_id';
    let filteringValue = this.clientOsProjectId;
    let api: FleioApiService<any>;
    switch (resourceType) {
      case 'Instances':
        api = this.instancesApiService;
        break;
      case 'Database instances':
        api = this.dbaasInstancesApiService;
        break;
      case 'SSH keys':
        filteringField = 'user__clients__id';
        filteringValue = this.object.id;
        api = this.publicKeysApiService;
        break;
      case 'Volumes':
        api = this.volumesApiService;
        break;
      case 'Networks':
        api = this.networksApiService;
        break;
      case 'Routers':
        api = this.routersApiService;
        break;
      case 'Images':
        api = this.imagesApiService;
        break;
      case 'Ports':
        api = this.portsApiService;
        break;
    }

    const queryParams = {
      filtering: `${filteringField}:${filteringValue}`,
      page_size: 10000,
    };

    this.disabledShowMoreButton[resourceType] = true;
    api.list(queryParams).subscribe(response => {
      // deep copy
      this.cloudSummary[resourceType].objects = JSON.parse(JSON.stringify(response.objects));
      this.cloudSummary[resourceType].count = response.count;
    }).add(() => {
      this.disabledShowMoreButton[resourceType] = false;
    });

  }

  protected tabActivated() {
    super.tabActivated();
    if (this.object) {
      this.loading = true;
      this.openstackBillingServicesApiService.getOpenstackServices(this.object.id).subscribe(servicesResponse => {
        if (servicesResponse.services.length) {
          this.service = servicesResponse.services[0];
          this.clientOsProjectId = servicesResponse.projects[this.service.id]?.project_id;
          this.clientsApiService.getCloudSummary(this.object.id).subscribe(cloudSummary => {
            this.cloudSummary = cloudSummary;
            this.cloudSummaryKeys = Object.keys(this.cloudSummary);
            this.loading = false;
          });
        } else {
          this.loading = false;
        }
      });
    }
  }
}
