import { Component, Input, OnInit } from '@angular/core';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { AbstractControl, FormControl } from '@angular/forms';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

export interface IClientsRetrieveParams {
  clientGroupId: FleioId;
}

@Component({
  selector: 'app-client-autocomplete',
  templateUrl: './client-autocomplete.component.html',
  styleUrls: ['./client-autocomplete.component.scss']
})
export class ClientAutocompleteComponent implements OnInit {
  @Input() control: FormControl | AbstractControl;
  @Input() clientsWithEnabledProject = false;
  @Input() optionsRetrieveParams: IClientsRetrieveParams;
  @Input() forClientGroup = false;
  @Input() overridePlaceholderUnselected: string;
  @Input() overridePlaceholderSelected: string;
  @Input() optionsQueryParams: Record<string, any> = {};
  placeholderUnselected = $localize`Select client ...`;
  placeholderSelected = $localize`Client`;
  switchMapHandler: (search: string) => Observable<any>;

  constructor(
    public clientsApiService: ClientsApiService,
  ) { }

  ngOnInit(): void {
    if (this.clientsWithEnabledProject !== false) {
      this.optionsQueryParams.has_enabled_project = true;
    }
    if (this.overridePlaceholderUnselected) {
      this.placeholderUnselected = this.overridePlaceholderUnselected;
    }
    if (this.overridePlaceholderSelected) {
      this.placeholderSelected = this.overridePlaceholderSelected;
    }

    if (this.forClientGroup !== false) {
      this.switchMapHandler = (search) => this.clientsApiService.getAvailableClientsForGroup(
          this.optionsRetrieveParams.clientGroupId, search,
        ).pipe(map(response => response.objects));
    }
  }

}
