import { AfterViewInit, Component, Input, OnInit } from '@angular/core';
import { AbstractControl, FormControl } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { AutocompleteHelper } from '@shared/ui-api/helpers/autocomplete-helper';

@Component({
  selector: 'app-country-autocomplete',
  templateUrl: './country-autocomplete.component.html',
  styleUrls: ['./country-autocomplete.component.scss']
})
export class CountryAutocompleteComponent implements OnInit, AfterViewInit {
  @Input() control: FormControl | AbstractControl;
  @Input() countries: Array<any>;
  switchMapHandler: (search: string) => Observable<any>;
  placeholderUnselected = $localize`Select country ...`;
  placeholderSelected = $localize`Country`;

  constructor() { }

  private normalizeValue(value): string {
    if (value?.label) {
      return value.label.toLowerCase().replace(/\s/g, '');
    } else {
      return value.toLowerCase().replace(/\s/g, '');
    }
  }

  private filterCountries(value: string): Observable<Array<string>> {
    const filterValue = this.normalizeValue(value);
    return of(this.countries.filter(
      country => this.normalizeValue(country).includes(filterValue)
    ));
  }

  ngOnInit(): void {
    this.switchMapHandler = (search) => this.filterCountries(search);
  }

  ngAfterViewInit() {
    if (this.control?.value) {
      // we're on some edit form, make sure values are filtered by what the input contains
      AutocompleteHelper.refreshAutocompleteOptions(this.control);
    }
  }

}
