import React from 'react';
import Router from 'react-router';
import routes from './views/routes';
import { Provider } from 'react-redux';

const getFetchData = (component) => {
  //need to check if the component is not undefined when using nested router without passing a component in props.
  return  (component && component.fetchData) || (component && component.DecoratedComponent && component.DecoratedComponent.fetchData);
};

export function createTransitionHook(store) {
  return (nextState, transition, callback) => {
    Promise.all(nextState.branch
      .map(route => route.component)
      .filter(component => {
        return getFetchData(component);
      })
      .map(getFetchData)
      .map(fetchData => {
        return fetchData(store, nextState.params);
      }))
      .then(() => {
        callback(); // can't just pass callback to then() because callback assumes first param is error
      }, (error) => {
        callback(error);
      });
  };
}

export default function universalRouter(location, history, store) {
  return new Promise((resolve, reject) => {
    Router.run(routes, location, [createTransitionHook(store)], (error, initialState, transition) => {
      if (error) {
        return reject(error);
      }

      if (transition && transition.redirectInfo) {
        return resolve({
          transition,
          isRedirect: true
        });
      }

      if (history) {  // only on client side
        initialState.history = history;
      }

      const component = (
        <Provider store={store} key="provider">
          {() => <Router {...initialState} children={routes}/>}
        </Provider>
      );

      return resolve({
        component,
        isRedirect: false
      });
    });
  });
}

@@ -164,16 +164,19 @@
 omponent
+=%7B%7D
 ) =%3E %7B%0A 
@@ -180,183 +180,64 @@
 %7B%0A  
-//need to check if the component is not undefined when using nested router without passing a component in props.%0A  return  (component && component.fetchData) %7C%7C (component && 
+return component.DecoratedComponent ? %0A    getFetchData(
 comp
@@ -264,32 +264,17 @@
 nent
- && component.DecoratedC
+) :%0A    c
 ompo
@@ -287,17 +287,16 @@
 etchData
-)
 ;%0A%7D;%0A%0Aex
@@ -475,38 +475,8 @@
 ter(
-component =%3E %7B%0A        return 
 getF
@@ -494,25 +494,16 @@
 mponent)
-;%0A      %7D
 )%0A      
@@ -544,33 +544,16 @@
 hData =%3E
- %7B%0A        return
  fetchDa
@@ -579,26 +579,16 @@
 .params)
-;%0A      %7D)
 )%0A      

update universal router getFetchState