/*
 Rookeries - Router and initialization for server-side rendering

 @copyright (c) Copyright 2013-2016 Dorian Pula
 @license AGPL v3
 @author Dorian Pula [dorian.pula@amber-penguin-software.ca]
 */

import React from "react";
import ReactDOMServerSide from "react-dom/server";
import {match, RouterContext, createMemoryHistory} from "react-router";
import {Provider} from "react-redux";
import {syncHistoryWithStore} from "react-router-redux";

import {appStore} from "../stores";
import {initializeApp} from "../actions";
import {Routes} from "./routes";


export function renderReactComponentsToString(url) {
    const memoryHistory = createMemoryHistory(url);
    const history = syncHistoryWithStore(memoryHistory, appStore);
    initializeApp(appStore);

    const renderedApp = {
        bodyContent: ""
    };

    match({history, routes: Routes, location: url}, (err, redirect, props) => {
        renderedApp.bodyContent = ReactDOMServerSide.renderToString(
            <Provider store={ appStore }>
                <RouterContext { ...props } />
            </Provider>
        );

    });

    return renderedApp;
}
