import { Component, ViewEncapsulation, ChangeDetectionStrategy, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IdName, filterIdNames } from '../../_shared/utils/util';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, of } from 'rxjs';
import { ControlBaseComponent, FilterValue } from '../control-base.component';
import { tap, switchMap } from 'rxjs/operators';
import { FilterControlService } from '../filter-control.service';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../../app.config';

@Component({
  selector: 'control-counterparty',
  templateUrl: './control-counterparty.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CommonModule,FAST_PAGE_COMMON, FAST_KENDO_COMMON]
})
export class ControlCounterpartyComponent extends ControlBaseComponent implements OnInit {
  http = inject(HttpClient);
  controlService = inject(FilterControlService);
  items: IdName[];
  virtual = { itemHeight: 28 };

  constructor() {
    super();
  }

  refreshItems$ = new BehaviorSubject<string>(null);

  ngOnInit(): void {
    super.ngOnInit();

    this.refreshItems$.next(null);
  }

  filterItems$ = new BehaviorSubject<string>(null)

  items$ = this.refreshItems$.pipe(
    switchMap(() => {
      return this.controlService.counterparties$.pipe(tap((x: IdName[]) => this.items = x));
    })
  )

  filteredItems$ = this.filterItems$.pipe(filterIdNames(of(false), this.items$, null));

  filterItems(filterStr: string) {
    this.filterItems$.next(filterStr);
  }

  getValue(): string {
    return this.mainCtrl.value?.length > 0 ? this.mainCtrl.value.join(',') : null;
  }

  getFilterValue(): FilterValue {
    const value1 = this.getValue();
    const preview = this.getPreview();
    const filterValue: FilterValue = { id: 0, name: this.parameterName, filterId: this.filterId, dataSourceId: this.dataSourceId, preview: preview, value1: value1, value2: null }
    return filterValue;
  }

  getPreview(): string {
    return this.getIdListPreview(this.mainCtrl.value, this.items);
  }

  setFilterValue(param: FilterValue) {
    this.mainCtrl.patchValue(param.value1.split(',').map(x => parseInt(x)));
    this.valueUpdated$.next(null);
    this.myRef.detectChanges();
  }

  resetValue() {
    this.form.reset();
    this.mainCtrl.patchValue([]);
    this.valueUpdated$.next(null);
    this.myRef.detectChanges();
  }

  valueChanged() {
    this.valueUpdated$.next(null);
  }
}
