import { ElementType } from 'react';
import { useSearchParams } from 'react-router-dom';
import { IndexSignature } from '../../utils';

export const WithHocSearchParams = (Component: ElementType) => {
  return function WithHocSearchParamsComponent({ ...props }: IndexSignature) {
    const [searchParams] = useSearchParams();
    const queries = Object.fromEntries(new URLSearchParams(searchParams));

    return (
      <Component
        searchParams={() => queries}
        queryFilterData={(data: any[]) => {
          return queries.search ? data.filter(datum => {
            let searchableDatum: string[] = [];

            Object.keys(datum).slice(1).forEach(attribute => {
              searchableDatum.push(String(datum[attribute]));
            });

            return searchableDatum.join(' ').toLowerCase()
              .indexOf(queries.search.toLowerCase()) >= 0;
          }) : data;
        }}
        {...props}
      />
    );
  };
};

export type SearchParamsType = () => any;
export type QueryFilterDataType = (data: any[]) => any[];
