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

export interface IUsersRetrieveParams {
  userGroupId: FleioId;
}

@Component({
  selector: 'app-user-autocomplete',
  templateUrl: './user-autocomplete.component.html',
  styleUrls: ['./user-autocomplete.component.scss']
})
export class UserAutocompleteComponent implements OnInit {
  @Input() control: FormControl | AbstractControl;
  @Input() overridePlaceholderUnselected: string;
  @Input() overridePlaceholderSelected: string;
  @Input() optionsRetrieveParams: IUsersRetrieveParams;

  @Input() staffUsersOnly = false;
  @Input() endUsersOnly = false;
  @Input() activeUsersOnly = false;
  @Input() optionsQueryParams: Record<string, any> = {};
  @Input() customSwitchMapHandler: (search: string) => Observable<any>;

  @Input() forUserGroup = false;
  placeholderUnselected = $localize`Select user ...`;
  placeholderSelected = $localize`User`;
  switchMapHandler: (search: string) => Observable<any>;

  constructor(
    public usersApiService: UsersApiService,
  ) { }

  ngOnInit(): void {
    if (this.staffUsersOnly !== false) {
      this.optionsQueryParams.is_staff = true;
    }
    if (this.endUsersOnly !== false) {
      this.optionsQueryParams.is_staff = false;
    }
    if (this.activeUsersOnly !== false) {
      this.optionsQueryParams.is_active = true;
    }
    if (this.overridePlaceholderUnselected) {
      this.placeholderUnselected = this.overridePlaceholderUnselected;
    }
    if (this.overridePlaceholderSelected) {
      this.placeholderSelected = this.overridePlaceholderSelected;
    }

    if (this.customSwitchMapHandler) {
      this.switchMapHandler = this.customSwitchMapHandler;
    } else {
      if (this.forUserGroup !== false) {
        this.switchMapHandler = (search) => this.usersApiService.getAvailableUsersForGroup(
          this.optionsRetrieveParams.userGroupId, search,
        ).pipe(map(response => response.objects));
      }
    }
  }

}
