import React, { useEffect, useState } from 'react';
import { useAppContext } from '../appContext/UseAppContext';
import { IPagination } from '../../models/IPagination';

export const usePagination = () => {
  const [pagination, setPagination] = useState<IPagination | null>(null);

  const getStoredValue = (): IPagination | null => {
    const storedPagination: string | null =
      sessionStorage.getItem('pagination');
    console.log(storedPagination);
    let pagination: IPagination;

    if (storedPagination) {
      return (pagination = JSON.parse(storedPagination));
    } else {
      return null;
    }
  };

  const removeStoredValue = () => {
    sessionStorage.removeItem('pagination');
    console.log('blah');
  };

  const onSessionStorageChanged = () => {
    setPagination(getStoredValue());
  };

  useEffect(() => {
    setPagination(getStoredValue());

    window.addEventListener('storage', onSessionStorageChanged);

    return () => {
      console.log('blah');
      window.removeEventListener('storage', onSessionStorageChanged);
    };
  }, []);

  return {
    pagination,
    removeStoredValue
  };
};
