import _ from "lodash";
import React from "react";
import Html from "../core/components/html";
import ReactDOMServer from "react-dom/server";

import WorkboxSW from "./libs/workbox-sw";
// As service worker has special scope for self lets store it to variable
// eslint-disable-next-line
const serviceWorker = self;

// ASSETS variable is inserted by dev.server.js & server.js on fly.

let WEB_ASSETS = serviceWorker.ASSETS || [];
let _GLOBALS = {};

self.addEventListener("install", (event) => {
  event.waitUntil(
    fetch("/_globals")
      .then(res => res.json())
      .then(data => {
        _GLOBALS = data;
        return Promise.resolve();
      })
  );
});

const getOfflineHtml = () => {
  console.log(_GLOBALS);
  const allCss = _.get(_GLOBALS, "allCss", []);
  const allJs = _.get(_GLOBALS, "allJs", []);
  
  /**
   * Get css generated by current route and module
   */
  const currentRouteCss = _.filter(allCss, css => {
    const fileName = css.split("/").pop();
    return !_.startsWith(fileName, "mod-");
  });
  
  /**
   * Get all javascript but the modules
   */
  const currentRouteJs = _.filter(allJs, js => {
    const fileName = js.split("/").pop();
    return !_.startsWith(fileName, "mod-") && !_.startsWith(fileName, "service-worker.js");
  });
  
  /**
   * Trying offline solution.
   */
  let html = ReactDOMServer.renderToString((
    <Html
      stylesheets={currentRouteCss}
      scripts={currentRouteJs}
    >
    </Html>
  ));
  return `<!DOCTYPE html>${html}`;
};

const workboxSW = new WorkboxSW({skipWaiting: true, clientsClaim: true});

workboxSW.precache(_.map(WEB_ASSETS, asset => { return {url: asset};}));

const networkFirstHandler = workboxSW.strategies.networkFirst();

workboxSW
  .router
  .registerRoute(
    /.*\.(css|bmp|tif|ttf|docx|woff2|js|pict|tiff|eot|xlsx|jpg|csv|eps|woff|xls|jpeg|doc|ejs|otf|pptx|gif|pdf|swf|svg|ps|ico|pls|midi|svgz|class|png|ppt|mid|webp|jar)/,
    workboxSW.strategies.cacheFirst()
  );

workboxSW
  .router
  .registerRoute(
    /_globals$/,
    workboxSW.strategies.cacheFirst()
  );

workboxSW.router.registerRoute(/.*/,  ({event}) => {
  return networkFirstHandler.handle({event})
    .then(response => {
      if (!response) {
        const request = event.request;
        if (
          request.url.indexOf(serviceWorker.location.origin) !== -1 &&
          request.method.toUpperCase() === "GET" &&
          request.headers.get("accept").indexOf("html") !== -1
        ) {
          return new Response(
            getOfflineHtml(),
            { headers: { "Content-Type": "text/html" }}
          );
        }
      }
      return response;
    });
});

@@ -698,33 +698,8 @@
 %3E %7B%0A
-  console.log(_GLOBALS);%0A
   co

Remove console.log in service worker