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

import { SelectionModel } from '@angular/cdk/collections';
import { User } from '../../../shared/user';
import { Filter, ListFilter } from '../filter/filter.model';
import { UserFilterService } from '../filter/user-filter.service';

/** WARNING: This FilterEntry model does not work nicely in case multiple entries share a common state.
 *  POSSIBLE SOLUTION: Use a comprehensive filter state cloned from the commandbar's / tables filter state and sync it back upon closing the sidebar.
 *  ...and please consider contributing it back to the BCI Web Core ;)
 */
export class FilterEntry {
  public active: boolean;
  // eslint-disable-next-line no-empty-function
  protected beforeApplyingDeactivation = () => {};
  // eslint-disable-next-line no-empty-function
  protected beforeApplyingActivation = () => {};

  constructor(
    public label: string,
    protected filterService: UserFilterService,
    public filter: Filter<User, any>,
    public icon?: string,
    public key?: string
  ) {
    this.init();
  }

  getValue(): string {
    return;
  }

  init() {
    this.active = this.isApplied();
  }

  applyComplexFilter(filterService: UserFilterService) {
    if (this.isApplied() && !this.active) {
      this.beforeApplyingDeactivation();
      filterService.deactivateFilters(this.filter);
    } else if (this.active) {
      this.beforeApplyingActivation();
      filterService.activateFilters(this.filter);
    }
  }

  apply(filterService: UserFilterService) {
    if (this.isApplied() && !this.active) {
      this.beforeApplyingDeactivation();
      filterService.deactivate(this.filter);
    } else if (this.active) {
      this.beforeApplyingActivation();
      filterService.activate(this.filter);
    }
  }

  deactivate() {
    this.active = false;
  }

  isApplied() {
    return this.filterService.isComplexFilterActive(this.filter);
  }
}

export class SelectionFilterEntry<Term> extends FilterEntry {
  protected beforeApplyingActivation = () => {
    this.filter.term = this.selectionModel.selected;
  };

  constructor(
    public label: string,
    protected filterService: UserFilterService,
    public filter: ListFilter<User, Term>,
    public selectionModel: SelectionModel<Term>,
    public icon?: string,
    public key?: string
  ) {
    super(label, filterService, filter, icon, key);

    this.selectionModel.changed.subscribe((state) => {
      this.active = state.source.hasValue();
    });
  }

  getValue(): string {
    return this.selectionModel.selected.join(', ');
  }

  deactivate() {
    this.selectionModel.clear();
    super.deactivate();
  }
}
