import { AlertOutlined } from "@ant-design/icons";
import { Button, notification, Space } from "antd";
import i18n from "i18next";
import * as serviceWorkerRegistration from "../serviceWorkerRegistration";
import { store } from "../redux/store";
import InstanceRenderManager from "./instanceRenderMgr";

const onServiceWorkerUpdate = (registration) => {
  console.log("onServiceWorkerUpdate", registration);

  const btn = (
    <Space flex>
      <Button
        onClick={async () => {
          window.open(`https://shopmanagement.canny.io/changelog`, "_blank");
        }}
      >
        {i18n.t("general.actions.viewreleasenotes")}
      </Button>
      <Button
        type="primary"
        onClick={async () => {
          if (registration?.waiting) {
            await registration.unregister();
            // Makes Workbox call skipWaiting()
            registration.waiting.postMessage({ type: "SKIP_WAITING" });
            // Once the service worker is unregistered, we can reload the page to let
            // the browser download a fresh copy of our app (invalidating the cache)
            window.location.reload();
          }
        }}
      >
        {i18n.t("general.actions.refresh")}
      </Button>
    </Space>
  );

  store.dispatch();

  notification.open({
    icon: <AlertOutlined />,
    title: i18n.t("general.messages.newversiontitle", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    }),
    description: i18n.t("general.messages.newversionmessage", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    }),
    duration: 0,
    btn,
    key: "updateavailable"
  });
};

serviceWorkerRegistration.register({ onUpdate: onServiceWorkerUpdate });
