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

export class LogAuthSearchFilter extends SearchFilter {
  firstName = '';
  lastName = '';
  middleName = '';
  address = '';
  idern = '';
  snils = '';
  series = '';
  number = '';
  dateFrom: Date | null = null;
  dateTo: Date | null = null;

  public countFilters(): number {
    let filtersCount = super.countFilters();
    if (this.firstName) {
      filtersCount++;
    }
    if (this.lastName) {
      filtersCount++;
    }
    if (this.middleName) {
      filtersCount++;
    }
    if (this.dateFrom || this.dateTo) {
      filtersCount++;
    }
    if (this.address) {
      filtersCount++;
    }
    if (this.idern) {
      filtersCount++;
    }
    if (this.snils) {
      filtersCount++;
    }
    if (this.series) {
      filtersCount++;
    }
    if (this.number) {
      filtersCount++;
    }
    return filtersCount;
  }

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

    return Object.assign(super.prepareRequestParams(), {
      firstname: this.firstName || undefined,
      lastname: this.lastName || undefined,
      middlename: this.middleName || undefined,
      address: this.address || undefined,
      idern: this.idern || undefined,
      snils: this.snils || undefined,
      series: this.series || undefined,
      number: this.number || 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.firstname) {
      this.firstName = String(query.firstname);
    }
    if (query.lastname) {
      this.lastName = String(query.lastname);
    }
    if (query.middlename) {
      this.middleName = String(query.middlename);
    }
    if (query.event) {
      this.address = String(query.address);
    }
    if (query.snils) {
      this.snils = String(query.snils);
    }
    if (query.idern) {
      this.idern = String(query.idern);
    }
    if (query.series) {
      this.series = String(query.series);
    }
    if (query.number) {
      this.number = String(query.number);
    }
    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();
    }
  }
}
