import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { ConfigService } from '@shared/config/config.service';
import { IImageModel } from '@fleio-api/openstack/model/image.model';
import { UntypedFormBuilder } from '@angular/forms';
import { IFlavorModel } from '@fleio-api/openstack/model/flavor.model';
import { ImagesApiService } from '@fleio-api/openstack/image/image-api.service';
import { FlavorsApiService } from '@fleio-api/openstack/flavor/flavors-api.service';
import { IFlavorGroupModel } from '@fleio-api/openstack/model/flavor-group.model';
import { FlavorGroupsApiService } from '@fleio-api/openstack/flavor-group/flavor-groups-api.service';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { AutocompleteHelper } from '@shared/ui-api/helpers/autocomplete-helper';

@Component({
  selector: 'app-image-details-flavors-assignment',
  templateUrl: './image-details-flavors-assignment.component.html',
  styleUrls: ['./image-details-flavors-assignment.component.scss']
})
export class ImageDetailsFlavorsAssignmentComponent extends DetailsComponentBase<IImageModel> implements OnInit {
  assignForm = this.formBuilder.group({
    flavor: [''],
    flavorGroup: [''],
  });
  flavors: FleioObjectsList<IFlavorModel>;
  flavorGroups: FleioObjectsList<IFlavorGroupModel>;

  currentFlavorPage = 1;
  currentFlavorGroupPage = 1;
  flavorColumns = ['id', 'name', 'region', 'actions'];
  flavorGroupColumns = ['id', 'name', 'actions'];

  flavorSelectedPlaceholder = $localize`Flavor`;
  flavorUnselectedPlaceholder = $localize`Select flavor ...`;
  flavorOptionsQueryParams: Record<string, string>;

  flavorGroupSelectedPlaceholder = $localize`Flavor group`;
  flavorGroupUnselectedPlaceholder = $localize`Select flavor group ...`;
  flavorGroupOptionsQueryParams: Record<string, string>;

  constructor(
    public config: ConfigService,
    public flavorsApiService: FlavorsApiService,
    public flavorGroupsApiService: FlavorGroupsApiService,
    private formBuilder: UntypedFormBuilder,
    private imagesApiService: ImagesApiService,
    private notificationService: NotificationService,
  ) {
    super();
  }

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

  refreshFlavors() {
    this.flavorsApiService.getFlavorsAssignedToImage(
      this.object.id, this.currentFlavorPage,
    ).subscribe(flavors => {
      this.flavors = flavors;
    });
  }

  refreshFlavorGroups() {
    this.flavorGroupsApiService.getFlavorGroupsAssignedToImage(
      this.object.id, this.currentFlavorGroupPage,
    ).subscribe(flavorGroups => {
      this.flavorGroups = flavorGroups;
    });
  }

  refreshFlavorsAndFlavorGroups() {
    this.refreshFlavors();
    this.refreshFlavorGroups();
  }

  ngOnInit(): void {
    super.ngOnInit();

    if (this.object) {
      this.refreshFlavorsAndFlavorGroups();

      this.flavorOptionsQueryParams = {
        filtering: `region:${this.object.region}+images__ne:${this.object.id}`
      };

      this.flavorGroupOptionsQueryParams = {
        filtering: `images__ne:${this.object.id}`
      };
    }
  }

  changeFlavorPage(action: string) {
    if (action === 'next') {
      this.currentFlavorPage = this.currentFlavorPage + 1;
      this.refreshFlavors();
    }
    if (action === 'previous') {
      this.currentFlavorPage = this.currentFlavorPage - 1;
      this.refreshFlavors();
    }
  };

  changeFlavorGroupPage(action: string) {
    if (action === 'next') {
      this.currentFlavorGroupPage = this.currentFlavorGroupPage + 1;
      this.refreshFlavorGroups();
    }
    if (action === 'previous') {
      this.currentFlavorGroupPage = this.currentFlavorGroupPage - 1;
      this.refreshFlavorGroups();
    }
  };

  assignFlavor() {
    const flavor = this.assignForm.controls.flavor.value as IFlavorModel;
    if (flavor && flavor.id) {
      this.flavorsApiService.addToImage(flavor.id, this.object.id).subscribe(() => {
        this.notificationService.showMessage($localize`Flavor assigned to image`);
        this.refreshFlavors();
        this.assignForm.controls.flavor.setValue('');
      });
    }
  }

  removeFlavor(flavorId: FleioId) {
    this.notificationService.confirmDialog({
      title: $localize`Remove flavor from image`,
      message: $localize`Are you sure you want to remove flavor ${flavorId} from image?`
    }).subscribe(result => {
      if (result?.button === 'yes') {
        this.flavorsApiService.removeFromImage(flavorId, this.object.id).subscribe(() => {
          this.notificationService.showMessage($localize`Flavor removed from image`);
          this.refreshFlavors();
          AutocompleteHelper.refreshAutocompleteOptions(this.assignForm.controls.flavor);
        });
      }
    });
  }

  assignFlavorGroup() {
    const flavorGroup = this.assignForm.controls.flavorGroup.value as IFlavorGroupModel;
    if (flavorGroup && flavorGroup.id) {
      this.flavorGroupsApiService.addToImage(flavorGroup.id, this.object.id).subscribe(() => {
        this.notificationService.showMessage($localize`Flavor group assigned to image`);
        this.refreshFlavorGroups();
        this.assignForm.controls.flavorGroup.setValue('');
      });
    }
  }

  removeFlavorGroup(flavorGroupId: FleioId) {
    this.notificationService.confirmDialog({
      title: $localize`Remove flavor group from image`,
      message: $localize`Are you sure you want to remove flavor group ${flavorGroupId} from image?`
    }).subscribe(result => {
      if (result?.button === 'yes') {
        this.flavorGroupsApiService.removeFromImage(flavorGroupId, this.object.id).subscribe(() => {
          this.notificationService.showMessage($localize`Flavor group removed from image`);
          this.refreshFlavorGroups();
          AutocompleteHelper.refreshAutocompleteOptions(this.assignForm.controls.flavorGroup);
        });
      }
    });
  }
}
