import React from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import { ServerApp } from '../../app';
import { getStyleTag } from '../styles';
import getAssetsArray from '../assets';
import DocumentComponent from './component';

const renderDocument = async (
  url,
  data,
  routes,
  ResourceHints,
  ServerStyleSheet, // pass in the ServerStyleSheet as it needs to remain a singleton - revist in https://github.com/bbc/SPArtacus/issues/41
  Helmet,
) => {
  const sheet = new ServerStyleSheet();

  const app = renderToString(
    sheet.collectStyles(
      <ServerApp location={url} routes={routes} data={data} context={{}} />,
    ),
  );

  const headHelmet = Helmet.renderStatic();
  const assets = getAssetsArray();
  const doc = renderToStaticMarkup(
    <DocumentComponent
      assets={assets}
      app={app}
      data={data}
      styleTags={getStyleTag(sheet, data.isAmp)}
      helmet={headHelmet}
      ResourceHints={ResourceHints}
    />,
  );

  return `<!doctype html>${doc}`;
};

export default renderDocument;
