import React, { createContext, useContext, useReducer } from 'react';

import initialMainState, { StateType as MainStateType } from './initialMainState';
import initialPdfState, { StateType as PdfStateType } from './initialPdfState';

import reducers from '../reducers'
import applyMiddleware from '../middleware';

type StateType = MainStateType & PdfStateType

type IContextProps = [
  StateType,
  ({type}:{type:string}) => void,
]

export const initialState = {
  ...initialMainState,
  ...initialPdfState
};

export const StateContext = createContext({} as IContextProps);

export const StoreProvider = ({
  children,
} : {
  children: React.ReactNode;
}) => {
  const [state, dispatch] = useReducer(reducers, initialState);
  const enhancedDispatch = applyMiddleware(dispatch);

  return (
    <StateContext.Provider
      value={[state, enhancedDispatch]}
      children={children}
    />
  );
};

export default () => useContext(StateContext);
