import React, { useState, useEffect } from 'react';
import packageJson from '../package.json';
import { compareAsc, getTime } from 'date-fns';
/**
 * @description: get the time time for the last deployed build and the current build
 * @param {*} latestDate
 * @param {*} currentDate
 */

const buildDateGreaterThan = (latestDate, currentDate) => {
  const latestDateTime = getTime(new Date(latestDate));
  const currentDateTime = getTime(new Date(currentDate));

  if (compareAsc(latestDateTime, currentDateTime) === -1) {
    return true;
  } else {
    return false;
  }
};

function WithClearCache(Component) {
  function ClearCacheComponent(props) {
    const [isLatestBuildDate, setIsLatestBuildDate] = useState(false);
    useEffect(() => {
      fetch('/meta.json')
        .then(response => response.json())
        .then(meta => {
          const latestVersionDate = meta.buildDate;
          const currentVersionDate = packageJson.buildDate;
          const shouldForceRefresh = buildDateGreaterThan(
            latestVersionDate,
            currentVersionDate
          );

          if (shouldForceRefresh) {
            setIsLatestBuildDate(false);
            refreshCacheAndReload(); // refresh cache
          } else {
            setIsLatestBuildDate(true);
          }
        });
    }, []);

    const refreshCacheAndReload = () => {
      if (caches) {
        // Service worker cache should be cleared with caches.delete()
        caches.keys().then(names => {
          for (const name of names) {
            caches.delete(name);
          }
        });
      } // delete browser cache and hard reload

      window.location.reload();
    };

    return /*#__PURE__*/ React.createElement(
      React.Fragment,
      null,
      isLatestBuildDate
        ? /*#__PURE__*/ React.createElement(Component, props)
        : /*#__PURE__*/ React.createElement('p', null)
    );
  }

  return ClearCacheComponent;
}

export default WithClearCache;
