import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { Router, Route, RoutingContext, match } from 'react-router';
import { Provider } from 'react-redux';
import createMemoryHistory from 'history/lib/createMemoryHistory';

import * as stylus from './assets/styles/index.styl';

import * as services from './services';

import routes from './routes';
import store from './store';

const base = require('babel!template-string!./base.tpl');
const staticRoutes = require('./static-routes');

// Server-side renderer
export default (locals, callback) => {
  const history = createMemoryHistory();
  const location = history.createLocation(locals.path);
  const scriptName = process.env.NODE_ENV === 'production' ? '/app.js' : '/app.js';
  const segmentKey = process.env.SEGMENT_KEY;
  const olarkSiteId = process.env.OLARK_SITE_ID;
  const stripePublishableKey = process.env.STRIPE_PUBLISHABLE_KEY;

  // These special paths are used by webpack-dev-server and S3 respectively.
  // They provide a 'blank slate' to load React non-isomorphically.
  if (locals.path === '/index.html' || locals.path === '/_init.html') {
    callback(null, base({appHTML: '', scriptName, segmentKey, olarkSiteId, stripePublishableKey}));
    return;
  }

  match({ routes, location }, (error, redirectLocation, renderProps) => {
    const appHTML = ReactDOMServer.renderToString(
      <Provider store={store}>
        <RoutingContext {...renderProps} />
      </Provider>
    );
    if (!staticRoutes[locals.path]) {
      throw new Error('missing static-route: ' + locals.path);
    }
    callback(null, base({appHTML, scriptName, segmentKey, olarkSiteId, stripePublishableKey}));
  });
};
