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 { IServiceModel } from '@fleio-api/billing/model/service.model';
import { IProjectModel } from '@fleio-api/openstack/project/model/project.model';
import { MatDialog } from '@angular/material/dialog';
import { ChangePricingPlanDialogComponent } from './dialogs/change-pricing-plan-dialog/change-pricing-plan-dialog.component';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { CreateOpenstackServiceDialogComponent } from './dialogs/create-openstack-service-dialog/create-openstack-service-dialog.component';
import {
  OpenstackBillingServicesApiService
} from '@fleio-api/openstack/billing/services/openstack-billing-services-api.service';

@Component({
  selector: 'app-client-details-openstack-service',
  templateUrl: './client-details-openstack-service.component.html',
  styleUrls: ['./client-details-openstack-service.component.scss']
})
export class ClientDetailsOpenstackServiceComponent extends DetailsComponentBase<IClientModel> implements OnInit {
  openstackServices: IServiceModel[];
  openstackProjects: { [serviceId: number]: IProjectModel };
  hasServiceWithProject = false;
  displayedColumns: string[] = ['date', 'destination', 'source', 'amount'];

  constructor(
    private clientsApi: ClientsApiService,
    private openstackBillingServicesApiService: OpenstackBillingServicesApiService,
    public config: ConfigService,
    private matDialog: MatDialog,
    private servicesApi: ServicesApiService,
    private notificationService: NotificationService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  ngOnInit() {
    super.ngOnInit();
  }

  protected refreshData() {
    this.openstackBillingServicesApiService.getOpenstackServices(this.object.id).subscribe(openstackServices => {
      this.hasServiceWithProject = false;
      this.openstackServices = openstackServices.services;
      for (const service of this.openstackServices) {
        if (service.status === 'active' || service.status === 'suspended') {
          this.hasServiceWithProject = true;
          break;
        }
      }
      this.openstackProjects = openstackServices.projects;
    });
  }

  changePricingPlan(service: IServiceModel) {
    this.matDialog.open(
      ChangePricingPlanDialogComponent, {
        data: {
          client: this.object,
          availablePlans: this.object.openstack_billing_plans,
          service,
        },
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.refreshData();
      }
    });
  }

  terminateService(service: IServiceModel) {
    this.notificationService.confirmDialog({
      title: $localize`Terminate service ${service.id}`,
      message: $localize`Are you sure?`,
      importantMessage: $localize`This will permanently delete data.`,
    }).subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.servicesApi.terminate(service.id).subscribe(() => {
          this.notificationService.showMessage($localize`Service termination scheduled`);
        });
      }
    });
  }

  createOpenstackService() {
    this.openstackBillingServicesApiService.getNewServiceData(this.object.id).subscribe({
      next: newServiceData => {
        this.matDialog.open(
          CreateOpenstackServiceDialogComponent, {
            data: {
              client: this.object,
              availableProducts: newServiceData.products,
            },
            autoFocus: false,
          }
        ).afterClosed().subscribe(result => {
          if (result) {
            this.refreshData();
          }
        });
      },
      error: (error) => {
        this.notificationService.showMessage(error.error.detail);
      }
    });
  }
}
