import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IClusterTemplateModel } from '@fleio-api/openstack/model/cluster-template.model';
import { UntypedFormBuilder } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';
import { IFlavorModel } from '@fleio-api/openstack/model/flavor.model';
import { ClusterTemplatesApiService } from '@fleio-api/openstack/cluster-template/cluster-templates-api.service';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-cluster-details-assigned-flavors',
  templateUrl: './cluster-details-assigned-flavors.component.html',
  styleUrls: ['./cluster-details-assigned-flavors.component.scss']
})
export class ClusterDetailsAssignedFlavorsComponent extends DetailsFormBase<IClusterTemplateModel> implements OnInit {
  assignedFlavorsForm = this.formBuilder.group({
    flavor: [null]
  });
  assignedFlavorGroupsForm = this.formBuilder.group({
    flavor_group: [null]
  });
  selectedFlavor = this.assignedFlavorsForm.controls.flavor;
  selectedFlavorGroup = this.assignedFlavorGroupsForm.controls.flavor_group;
  displayedColumnsFlavors = ['id', 'name', 'region', 'actions'];
  displayedColumnsFlavorGroups = ['id', 'name', 'actions'];
  removeAssignmentTxt = $localize`Remove assignment`;

  flavorSelectedPlaceholder = $localize`Flavor`;
  flavorUnselectedPlaceholder = $localize`Select flavor ...`;
  flavorOptionsSwitchMap: (search: string) => Observable<any>;

  flavorGroupSelectedPlaceholder = $localize`Flavor group`;
  flavorGroupUnselectedPlaceholder = $localize`Select flavor group ...`;
  flavorGroupOptionsSwitchMap: (search: string) => Observable<any>;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private clusterTemplatesApiService: ClusterTemplatesApiService,
    private notificationService: NotificationService,
    public config: ConfigService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  protected refreshData() {
    this.clusterTemplatesApiService.get(this.object.id).subscribe(result => {
      this.objectController.object = result;
    });
  }

  assignFlavorToClusterTemplate() {
    const value = this.assignedFlavorsForm.value;
    if (value.flavor && value.flavor.id) {
      const dialogResult$ = this.notificationService.confirmDialog({
        title: $localize`Assign flavor ${value.flavor.name} to cluster template?`,
        message: $localize`Are you sure?`,
      });
      dialogResult$.subscribe(dialogResult => {
        if (dialogResult?.button === 'yes') {
          this.clusterTemplatesApiService.assignFlavorToClusterTemplate(
            this.object.id,
            value.flavor.id
          ).subscribe(() => {
            this.refreshData();
            this.assignedFlavorsForm.get('flavor').setValue(null);
          }, () => {
            this.refreshData();
            this.notificationService.showMessage($localize`Could not add flavor to cluster template.`);
          });
        }
      });
    } else {
      this.notificationService.showMessage($localize`Please select a valid flavor.`);
    }
  }

  assignFlavorGroupToClusterTemplate() {
    const value = this.assignedFlavorGroupsForm.value;
    if (value.flavor_group && value.flavor_group.id) {
      const dialogResult$ = this.notificationService.confirmDialog({
        title: $localize`Assign flavor group ${value.flavor_group.name} to cluster template?`,
        message: $localize`Are you sure?`,
      });
      dialogResult$.subscribe(dialogResult => {
        if (dialogResult?.button === 'yes') {
          this.clusterTemplatesApiService.assignFlavorGroupToClusterTemplate(
            this.object.id,
            value.flavor_group.id
          ).subscribe(() => {
            this.refreshData();
            this.assignedFlavorGroupsForm.get('flavor_group').setValue(null);
          }, () => {
            this.refreshData();
            this.notificationService.showMessage($localize`Could not add flavor group to cluster template.`);
          });
        }
      });
    } else {
      this.notificationService.showMessage($localize`Please select a valid flavor group.`);
    }
  }

  removeFlavor(flavorId) {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Remove assignment between flavor and cluster template?`,
      message: $localize`Are you sure?`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.clusterTemplatesApiService.removeFlavorFromClusterTemplate(
          this.object.id, flavorId
        ).subscribe(response => {
          this.refreshData();
        }, error => {
          this.refreshData();
          this.notificationService.showMessage($localize`Could not remove flavor from cluster template.`);
        });
      }
    });
  }

  removeFlavorGroup(flavorId) {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Remove assignment between flavor group and cluster template?`,
      message: $localize`Are you sure?`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.clusterTemplatesApiService.removeFlavorGroupFromClusterTemplate(
          this.object.id, flavorId
        ).subscribe(() => {
          this.refreshData();
        }, error => {
          this.refreshData();
          this.notificationService.showMessage($localize`Could not remove flavor group from cluster template.`);
        });
      }
    });
  }

  flavorDisplay(flavor?: IFlavorModel): string {
    if (flavor) {
      return `${flavor.name} - ${flavor.region}`;
    } else {
      return '';
    }
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.flavorOptionsSwitchMap = (search) => this.clusterTemplatesApiService.getAvailableFlavorsToAssign(
        this.object.id,
        search
      ).pipe(map(flavorsList => flavorsList.objects));
    this.flavorGroupOptionsSwitchMap = (search) => this.clusterTemplatesApiService.getAvailableFlavorGroupsToAssign(
        this.object.id, search
      ).pipe(map(flavorGroupsList => flavorGroupsList.objects));
  }

}
