import React from 'react';
import { addCallback } from 'meteor/vulcan:core';
import JssProvider from 'react-jss/lib/JssProvider';
import { MuiThemeProvider, createGenerateClassName } from '@material-ui/core/styles';
import forumTheme from '../../themes/forumTheme'
import { SheetsRegistry } from 'react-jss/lib/jss';
import JssCleanup from '../../components/themes/JssCleanup';

function wrapWithMuiTheme (app, { req, res, store, apolloClient }) {
  const sheetsRegistry = new SheetsRegistry();
  req.sheetsRegistry = sheetsRegistry;
  const generateClassName = createGenerateClassName({
    dangerouslyUseGlobalCSS: true
  });

  return (
    <JssProvider registry={sheetsRegistry} generateClassName={generateClassName}>
      <MuiThemeProvider theme={forumTheme} sheetsManager={new Map()}>
        <JssCleanup>
          {app}
        </JssCleanup>
      </MuiThemeProvider>
    </JssProvider>
  );
}


function injectJss ({ req, res }) {
  const sheets = req.sheetsRegistry.toString();
  req.dynamicHead = req.dynamicHead || '';
  req.dynamicHead += `<style id="jss-server-side">${sheets}</style>`;
}


addCallback('router.server.wrapper', wrapWithMuiTheme);
addCallback('router.server.postRender', injectJss);

@@ -372,16 +372,449 @@
 anup';%0A%0A
+const MuiThemeProviderWrapper = (props, context) =%3E %7B%0A  // By experimentation, it turns out that context.client is only available to this component%0A  // during the initial %60getDataFromTree%60 render, during which we want to skip%0A  // style-generation. See https://github.com/mui-org/material-ui/issues/8522%0A  return %3CMuiThemeProvider %7B...props%7D disableStylesGeneration=%7B!!context.client%7D%3E%0A    %7Bprops.children%7D%0A  %3C/MuiThemeProvider%3E%0A%7D%0A%0A
 function
@@ -1171,16 +1171,23 @@
 Provider
+Wrapper
  theme=%7B
@@ -1280,24 +1280,24 @@
 JssCleanup%3E%0A
-
       %3C/MuiT
@@ -1304,24 +1304,31 @@
 hemeProvider
+Wrapper
 %3E%0A    %3C/JssP

Disable styles generation during Apollo `getDataFromTree` pass