import {
  Behavior,
  FilterOperation,
  FilterUtil,
  Grid,
  LinkField,
  NotNull,
  ObjectRef
} from "@webbpm/base-package";

export class ErvuAvailableGridFilter extends Behavior {

  @ObjectRef()
  @NotNull()
  public existingRowsField: LinkField;

  private grid: Grid;
  private onChangeFunction: Function;

  public initialize() {
    super.initialize();
    this.grid = this.getScript(Grid);
    this.onChangeFunction = () => {
      let values: any[] = this.existingRowsField.getValue();
      let filter = FilterUtil.singleValueFilter(this.grid.getObjectId(), values || [],
                                                FilterOperation.NOT_IN);
      this.grid.reload([filter]);
    }
  }

  public bindEvents(): void {
    super.bindEvents();
    this.existingRowsField.addChangeListener(this.onChangeFunction);
  }

  public unbindEvents() {
    super.unbindEvents();
    this.existingRowsField.removeChangeListener(this.onChangeFunction);
  }
}
