import React from 'react';
import { createSubscriptionHook } from '@ywfe/hook-subscription';
import {RouterContext} from './context';
import {initialState, reducer} from './reducer';
import {RouterState, RouterAction} from './reducer.interface';
import { RouterContextProps, YRouterProps } from './router.interface';

export const RouterProvider: React.FC<YRouterProps> = ({children, config}) => {
  const contextValue = {
    store: createSubscriptionHook<RouterState, RouterAction>(reducer as any, initialState),
    useGetModuleDataByName: config.useGetModuleDataByName
  }

  const childs = React.Children.map(children, child => {
    return React.cloneElement(
      child as React.FunctionComponentElement<RouterContextProps>,
    );
  });

  return (
    <RouterContext.Provider value={contextValue}>
      {childs}
    </RouterContext.Provider>
  );
}
