import moment from 'moment';
import { SearchFilter, UrlQueryParams } from '@/recruits/models';

export class LogObjectSearchFilter extends SearchFilter {
  objectType = '';
  objectDescription = '';
  type = '';
  vkFio = '';
  dateFrom: Date | null = null;
  dateTo: Date | null = null;

  public countFilters(): number {
    let filtersCount = super.countFilters();
    if (this.dateFrom || this.dateTo) {
      filtersCount++;
    }
    if (this.objectType) {
      filtersCount++;
    }
    if (this.objectDescription) {
      filtersCount++;
    }
    if (this.type) {
      filtersCount++;
    }
    if (this.vkFio) {
      filtersCount++;
    }
    return filtersCount;
  }

  public prepareRequestParams(): UrlQueryParams {
    const datefrom = moment(this.dateFrom);
    const dateto = moment(this.dateTo);

    return Object.assign(super.prepareRequestParams(), {
      objecttype: this.objectType || undefined,
      objectdescription: this.objectDescription || undefined,
      type: this.type || undefined,
      vkfio: this.vkFio || undefined,
      datefrom:
        (datefrom.isValid() && datefrom.format('YYYY-MM-DD')) || undefined,
      dateto: (dateto.isValid() && dateto.format('YYYY-MM-DD')) || undefined,
    });
  }

  public updateParamsFromRoute(query: { [key: string]: string }): void {
    super.updateParamsFromRoute(query);
    if (query.objecttype) {
      this.objectType = String(query.objecttype);
    }
    if (query.objectdescription) {
      this.objectDescription = String(query.objectdescription);
    }
    if (query.type) {
      this.type = String(query.type);
    }
    if (query.vkfio) {
      this.vkFio = String(query.vkfio);
    }
    if (query.datefrom) {
      const dateFrom = moment(String(query.datefrom));
      if (dateFrom.isValid()) this.dateFrom = dateFrom.toDate();
    }
    if (query.dateto) {
      const dateTo = moment(String(query.dateto));
      if (dateTo.isValid()) this.dateTo = dateTo.toDate();
    }
  }
}
