import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IFlavorModel } from '@fleio-api/openstack/model/flavor.model';
import { UntypedFormBuilder } from '@angular/forms';
import { map } from 'rxjs/operators';
import { ClientGroupsApiService } from '@fleio-api/client-user/client-group/client-groups-api.service';
import { FlavorsApiService } from '@fleio-api/openstack/flavor/flavors-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-show-to-client-groups-form',
  templateUrl: './show-to-client-groups-form.component.html',
  styleUrls: ['./show-to-client-groups-form.component.scss']
})
export class ShowToClientGroupsFormComponent extends DetailsFormBase<IFlavorModel> implements OnInit {
  showToClientGroupsForm = this.formBuilder.group({
    clientGroup: ['']
  });
  clientGroup = this.showToClientGroupsForm.controls.clientGroup;
  displayedColumns = ['id', 'name', 'actions'];
  dissociateTooltip = $localize`Dissociate client group from flavor`;
  clientGroupSelectedPlaceholder = $localize`Client group`;
  clientGroupUnselectedPlaceholder = $localize`Select client group ...`;
  clientGroupOptionsSwitchMap: (search: string) => Observable<any>;

  constructor(
    private formBuilder: UntypedFormBuilder,
    public clientGroupsApiService: ClientGroupsApiService,
    private flavorsApiService: FlavorsApiService,
    private notificationService: NotificationService,
    public config: ConfigService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

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

  assignGroupToFlavor() {
    const value = this.showToClientGroupsForm.value;
    if (value.clientGroup && value.clientGroup.id) {
      const dialogResult$ = this.notificationService.confirmDialog({
        title: $localize`Assign client group ${value.clientGroup.name} to flavor?`,
        message: $localize`Are you sure?`,
      });
      dialogResult$.subscribe(dialogResult => {
        if (dialogResult?.button === 'yes') {
          this.objectController.loading = true;
          this.flavorsApiService.assignClientGroupToFlavor(
            this.object.id,
            value.clientGroup.id
          ).subscribe(response => {
            this.refreshData();
            this.clientGroup.setValue('');
          }, error => {
            this.refreshData();
            this.notificationService.showMessage($localize`Could not add client group to flavor.`);
          }).add(() => {
            this.objectController.loading = false;
          });
        }
      });
    } else {
      this.notificationService.showMessage($localize`Please select a valid client group.`);
    }
  }

  removeGroup(groupId) {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Remove client group from flavor?`,
      message: $localize`Are you sure?`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.flavorsApiService.removeClientGroupFromFlavor(this.object.id, groupId).subscribe(response => {
          this.refreshData();
        }, error => {
          this.refreshData();
          this.notificationService.showMessage($localize`Could not remove client group from flavor.`);
        });
      }
    });
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.clientGroupOptionsSwitchMap = (search) => this.flavorsApiService.getAvailableClientGroupsToAssign(
          this.object.id, search
        ).pipe(map(clientGroupsList => clientGroupsList.objects));
  }

}
