import { Collection, ICollection } from "../../Collection";
import { Result } from "../../Result";
import { Filter } from "./Filter";

export interface IFilterCollection extends ICollection<Filter> {
  findByField(field: string): Filter | undefined;
  removeByField(field: string): void;
  toObject(): Record<string, any>;
}

export class FilterCollection
  extends Collection<Filter>
  implements IFilterCollection
{
  static create(filters?: Filter[]): Result<FilterCollection> {
    return Result.ok<FilterCollection>(new FilterCollection(filters));
  }

  protected constructor(initialValues?: Filter[]) {
    super(initialValues, undefined);
  }

  public findByField(field: string): Filter | undefined {
    return this.find((filter) => filter.field === field);
  }

  public removeByField(field: string): void {
    let indexFound = -1;
    this.find((filter, index) =>
      filter.field === field ? (indexFound = index) : null,
    );
    if (indexFound > -1) {
      this.removeByIndex(indexFound);
    }
  }

  public toObject(): Record<string, any> {
    return this.items.map((filter: Filter) => filter.toObject());
  }
}
