import DocumentTitle from 'react-document-title';
import axios from 'axios';
import Html from './html.react';
import Promise from 'bluebird';
import React from 'react';
import Router from 'react-router';
import config from './config';
import initialState from './initialstate';
import routes from '../client/routes';
import {state} from '../client/state';


export default function render(req, res, locale) {
  const path = req.path;
  return loadData(path, locale)
    .then((appState) => renderPage(res, appState, path));
}

function loadData(path, locale) {
  // TODO: Preload and merge user specific state.
  const appState = initialState;
  return axios.get('https://www.wehkamp.com/nlbe/api/products?categoryPath=%2Fdamesmode%2Fblouses-tunieken%2F&page=1')
    .then((ajaxResponse) => {
      appState.products = ajaxResponse.data.products
        .map((product) => {
          return {
            title: product.websiteDescription,
            productId: product.productNumber,
            src: 'https://assets.wehkamp.com/i/wehkamp/' + product.productNumber + '_pb_01/' + product.normalizedName + '.jpg?$product300x300$'
          }
        });
      return appState;
    });
}

// TODO: Refactor.
function renderPage(res, appState, path) {
  return new Promise((resolve, reject) => {
    const router = Router.create({
      routes,
      location: path,
      onError: reject,
      onAbort: (abortReason) => {
        if (abortReason.constructor.name === 'Redirect') {
          const {to, params, query} = abortReason;
          const path = router.makePath(to, params, query);
          res.redirect(path);
          resolve();
          return;
        }
        reject(abortReason);
      }
    });
    router.run((Handler, routerState) => {
      state.load(appState);
      const html = getPageHtml(Handler, appState);
      const notFound = routerState.routes.some(route => route.name === 'not-found');
      const status = notFound ? 404 : 200;
      res.status(status).send(html);
      resolve();
    });
  });
}

function getPageHtml(Handler, appState) {
  const appHtml = `<div id="app">${React.renderToString(<Handler />)}</div>`;
    const appScriptSrc = config.isProduction
    ? '/build/app.js?v=' + config.version
    : '//localhost:8888/build/app.js';

    let scriptHtml = `
    <script>
    (function() {
    window._appState = ${JSON.stringify(appState)};
    var app = document.createElement('script'); app.type = 'text/javascript'; app.async = true;
    var src = '${appScriptSrc}';
    // IE<11 and Safari need Intl polyfill.
    if (!window.Intl) src = src.replace('.js', 'intl.js');
    app.src = src;
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(app, s);
  })();
    </script>`;

    if (config.isProduction && config.googleAnalyticsId !== 'UA-XXXXXXX-X')
    scriptHtml += `
    <script>
    (function(b,o,i,l,e,r){b.GoogleAnalyticsObject = l;b[l]||(b[l]=
    function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
    e=o.createElement(i);r=o.getElementsByTagName(i)[0];
    e.src='//www.google-analytics.com/analytics.js';
    r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
    ga('create','${config.googleAnalyticsId}');ga('send','pageview');
    </script>`;

    const title = DocumentTitle.rewind();

    return '<!DOCTYPE html>' + React.renderToStaticMarkup(
    <Html
    bodyHtml={appHtml + scriptHtml}
    isProduction={config.isProduction}
    title={title}
    version={config.version}
    />
    );
    }

@@ -414,23 +414,29 @@
 nst 
-path
+url
  = req.
-path
+originalUrl
 ;%0A  
@@ -443,36 +443,35 @@
 return loadData(
-path
+url
 , locale)%0A    .t
@@ -514,20 +514,19 @@
 pState, 
-path
+url
 ));%0A%7D%0A%0Af
@@ -542,20 +542,19 @@
 oadData(
-path
+url
 , locale

fix server not parsing get parameter