import { Criteria as BaseCriteria, Filters, FiltersPrimitives, Order } from "@codelytv/criteria";
import { INITIAL_PAGE_INDEX, INITIAL_PAGE_SIZE } from "./defaults";

export class Criteria extends BaseCriteria {
  /**
   * Creates a new Criteria instance.
   *
   * @param quickSearch - 'Quicksearch' field.
   * @param filters - The filters to apply.
   * @param order - The order to apply.
   * @param pageSize - The size of the page.
   * @param pageNumber - The number of the page.
   *
   */

  protected constructor(
    public readonly filters: Filters,
    public readonly order: Order,
    public readonly pageSize: number,
    public readonly pageNumber: number,
    public readonly quickSearch?: string //Texto libre para búsqueda rápida
  ) {
    super(filters, order, pageSize, pageNumber);
  }

  static fromPrimitives(
    filters: FiltersPrimitives[],
    orderBy: string | null,
    orderType: string | null,
    pageSize: number | null,
    pageNumber: number | null,
    quickSearch?: string | null
  ): Criteria {
    return new Criteria(
      Filters.fromPrimitives(filters),
      Order.fromPrimitives(orderBy, orderType),
      pageSize ?? INITIAL_PAGE_SIZE,
      pageNumber ?? INITIAL_PAGE_INDEX,
      quickSearch ?? undefined
    );
  }

  toPrimitives() {
    return {
      q: this.quickSearch ?? "",
      filters: this.filters.toPrimitives(),
      orderBy: this.order.orderBy.value,
      orderType: this.order.orderType.value,
      pageSize: this.pageSize,
      pageNumber: this.pageNumber,
    };
  }

  toJSON() {
    return this.toPrimitives();
  }
}
