import { ChangeDetectionStrategy, Component } from '@angular/core';
import { AvropService } from '@msfa-services/avrop.service';
import { MultiselectFilterOption } from '@msfa-shared/components/multiselect/multiselect-filter-option';
import { combineLatest, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'msfa-avrop-filters',
  templateUrl: './avrop-filters.component.html',
  styleUrls: ['./avrop-filters.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AvropFiltersComponent {
  availableTjanster$: Observable<MultiselectFilterOption[]> = this.avropService.availableTjanster$;
  availableUtforandeVerksamheter$: Observable<MultiselectFilterOption[]> = this.avropService
    .availableUtforandeVerksamheter$;
  availableKommuner$: Observable<MultiselectFilterOption[]> = this.avropService.availableKommuner$;
  filteredTjanster$: Observable<MultiselectFilterOption[]> = this.avropService.filteredTjanster$;
  filteredUtforandeVerksamheter$: Observable<MultiselectFilterOption[]> = this.avropService
    .filteredUtforandeVerksamheter$;
  filteredKommuner$: Observable<MultiselectFilterOption[]> = this.avropService.filteredKommuner$;

  filtersAreLoading$: Observable<boolean> = combineLatest([
    this.availableKommuner$,
    this.availableTjanster$,
    this.availableUtforandeVerksamheter$,
  ]).pipe(map(([kommuner, tjanster, uv]) => !!(kommuner && tjanster && uv)));

  constructor(private avropService: AvropService) {}

  updateSelectedTjanster(filterOptions: MultiselectFilterOption[]): void {
    this.avropService.setSelectedTjanster(filterOptions);
  }

  updateSelectedUtforandeVerksamheter(filterOptions: MultiselectFilterOption[]): void {
    this.avropService.setSelectedUtforandeVerksamheter(filterOptions);
  }

  updateSelectedKommuner(filterOptions: MultiselectFilterOption[]): void {
    this.avropService.setSelectedKommuner(filterOptions);
  }

  removeKommun(kommunToRemove: MultiselectFilterOption): void {
    this.avropService.removeKommun(kommunToRemove);
  }

  removeUtforandeVerksamhet(utforandeVerksamhetToRemove: MultiselectFilterOption): void {
    this.avropService.removeUtforandeVerksamhet(utforandeVerksamhetToRemove);
  }

  removeTjanst(tjanstToRemove: MultiselectFilterOption): void {
    this.avropService.removeTjanst(tjanstToRemove);
  }
}
