import {Component, Input, OnInit} from '@angular/core';
import {BaseFilterCellComponent, FilterService} from '@progress/kendo-angular-grid';
import {CompositeFilterDescriptor} from '@progress/kendo-data-query';
import {debounce} from 'ts-debounce';

@Component({
  selector: 'app-string-filter',
  templateUrl: './string-filter.component.html',
  styleUrls: ['./string-filter.component.scss']
})
export class StringFilterComponent extends BaseFilterCellComponent implements OnInit {
  @Input() public filter: CompositeFilterDescriptor;
  @Input() data = '';
  @Input() fieldName = '';
  public debouncedFilter = debounce(this.doFilter, 500);
  constructor(filterService: FilterService) { super(filterService); }

  ngOnInit(): void {
  }

  public onValueChange(v: string): void {
    if ( this.fieldName !== '' ){
      this.debouncedFilter(v).then();
    }
  }

  public doFilter(v: string): void {
    this.applyFilter(
      v === '' || v === null ?
        this.removeFilter(this.fieldName) :
        this.updateFilter({
          field: this.fieldName,
          operator: 'contains',
          value: v
        })
    );
  }
}
