import { Subject } from 'rxjs';
import { Filter } from './filter';

export interface IOrderBy {
  by?: string;
  desc?: boolean;
  label?: string;
  selected?: boolean;
}

export class OrderBy implements IOrderBy {
  //#region implements IUiFilterOrderByDTO
  private _by?: string;
  get by() {
    return this._by;
  }

  private _desc?: boolean;
  get desc() {
    return this._desc;
  }

  private _label?: string;
  get label() {
    return this._label;
  }

  private _selected?: boolean;
  get selected() {
    return this._selected;
  }

  //#endregion

  constructor(public readonly parent?: Filter) {}

  readonly changes = new Subject<{ keys: (keyof IOrderBy)[]; orderBy: OrderBy }>();

  setSelected(value: boolean, { emitEvent }: { emitEvent: boolean } = { emitEvent: true }) {
    if (this.selected !== value) {
      this._selected = value;

      if (emitEvent) {
        this.changes.next({ keys: ['selected'], orderBy: this });
      }
    }
  }

  toObject(): IOrderBy {
    return {
      by: this.by,
      desc: this.desc,
      label: this.label,
      selected: this.selected,
    };
  }

  static create(orderBy: IOrderBy, parent?: Filter) {
    const target = new OrderBy(parent);

    target._by = orderBy?.by;
    target._desc = orderBy?.desc;
    target._label = orderBy?.label;
    target._selected = orderBy?.selected;

    return target;
  }
}
