/*
 * Copyright (C) 2023 Robert Bosch GmbH Copyright (C) 2023 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { BciPicklistCompare, BciPicklistFilter } from '@bci-web-core/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { Fruit, fruits } from '../bci-core-picklist-demo-model';

/** This demo shows how to use a custom filter. */
@Component({
  selector: 'bci-custom-filter',
  templateUrl: './custom-filter.component.html',
  styleUrls: ['./custom-filter.component.scss'],
})
export class CustomFilterComponent implements OnInit, OnDestroy {
  fruitsControl = new FormControl();
  fruitsList = fruits;
  originList = this.fruitsList
    .map((fruit) => fruit.fromOverseas)
    .filter((fruit, index, src) => src.indexOf(fruit) === index);

  /** Display property name of objects in list of fruits. */
  displayProperty = 'name';

  fruitsFilter = new BehaviorSubject<BciPicklistFilter>(Boolean);

  private ngUnsubscribe = new Subject<void>();

  ngOnInit(): void {
    this.fruitsControl.valueChanges.pipe(takeUntil(this.ngUnsubscribe)).subscribe((value) => {
      this.fruitsFilter.next((item: Fruit) => {
        const selection = <boolean[]>value;
        if (!selection.length) {
          return true;
        } else {
          return (selection.includes(true) && item.fromOverseas) || (selection.includes(false) && !item.fromOverseas);
        }
      });
    });
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  sourceSort: BciPicklistCompare = (a: Fruit, b: Fruit): number => {
    if (a.fromOverseas === b.fromOverseas) {
      return a.name.localeCompare(b.name);
    } else {
      return a.fromOverseas && !b.fromOverseas ? -1 : 1;
    }
  };
}
