
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import useFetch from './Fetch';

const DataContext = React.createContext(null as any);

export function useDataContext() {
  return useContext(DataContext);
}

export const DataContextProvider = DataContext.Provider;

export default function useDataTable(url: string|false|null|undefined, defaultParams: any = null, body: any = null) {
  const [ params, setParams ] = useState<any>({
    page: 1,
    itemPerPage: 20,
    query: "",
    sort: "id",
    desc: false,
    ...defaultParams
  });

  const [ data,,,update ] = useFetch(url, params, body);

  const isInitialMount = useRef(true);

  useEffect(function() {
    if (isInitialMount.current) {
      isInitialMount.current = false;
    } else {
      setParams(params => ({ ...params, ...defaultParams, page: 1 }));
    }
  }, [isInitialMount, setParams, defaultParams]);

  const setPage = useCallback(function(page) {
    setParams(params => ({ ...params, page: +page }));
  }, [setParams]);

  const setItemPerPage = useCallback(function(itemPerPage) {
    setParams(params => ({ ...params, page: 1, itemPerPage: +itemPerPage }));
  }, [setParams]);

  return [
    (data && (data.currentPage || data.current_page || 0)) || params.page,
    data && (data.pageCount || data.last_page || 0),
    setPage,
    data && data.data,
    +params.itemPerPage,
    setItemPerPage,
    update,
    +((data && (data.itemCount || data.total || data.recordsFiltered || data.recordsTotal)) || 0)
  ];
}
