import react from "@vitejs/plugin-react";
import { promises as fsPromises } from "fs";
import { createRequire } from "module";
import * as path from "path";
import * as url from "url";
import { defineConfig } from "vite";
import { ViteEjsPlugin } from "vite-plugin-ejs";
import eslint from 'vite-plugin-eslint';

//import CompressionPlugin from 'vite-plugin-compression';
import { VitePWA } from "vite-plugin-pwa";
import InstanceRenderManager from "./src/utils/instanceRenderMgr";

process.env.VITE_APP_GIT_SHA_DATE = new Date().toLocaleString("en-US", {
  timeZone: "America/Los_Angeles"
});

const WRONG_CODE = `import { bpfrpt_proptype_WindowScroller } from "../WindowScroller.js";`;
function reactVirtualized() {
  return {
    name: "flat:react-virtualized",
    configResolved: async () => {
      const require = createRequire(import.meta.url);
      const reactVirtualizedPath = require.resolve("react-virtualized");
      const { pathname: reactVirtualizedFilePath } = new url.URL(reactVirtualizedPath, import.meta.url);
      const file = reactVirtualizedFilePath.replace(
        path.join("dist", "commonjs", "index.js"),
        path.join("dist", "es", "WindowScroller", "utils", "onScroll.js")
      );
      const code = await fsPromises.readFile(file, "utf-8");
      const modified = code.replace(WRONG_CODE, "");
      await fsPromises.writeFile(file, modified);
    }
  };
}

export default defineConfig({
  base: "/",
  plugins: [
    ViteEjsPlugin((viteConfig) => {
      // viteConfig is the current Vite resolved config
      return { env: viteConfig.env };
    }),
    VitePWA({
      injectRegister: "auto",
      registerType: "prompt",
      manifest: {
        short_name: InstanceRenderManager({
          instance: process.env.VITE_APP_INSTANCE,
          imex: "ImEX Online",
          rome: "Rome Online",
          promanager: "ProManager"
        }),
        name: InstanceRenderManager({
          instance: process.env.VITE_APP_INSTANCE,
          imex: "ImEX Online",
          rome: "Rome Online",
          promanager: "ProManager"
        }),
        description: "The ultimate bodyshop management system.",
        icons: [
          {
            //TODO:AIO Ensure that these are correct for Rome and IO.
            src: InstanceRenderManager({
              instance: process.env.VITE_APP_INSTANCE,
              imex: "favicon.png",
              rome: "ro-favicon.png",
              promanager: "/pm/pm-favicon.ico"
            }),
            sizes: "64x64 32x32 24x24 16x16",
            type: "image/x-icon"
          },
          {
            src: InstanceRenderManager({
              instance: process.env.VITE_APP_INSTANCE,
              imex: "logo192.png",
              rome: "logo192.png",
              promanager: "/pm/pm-icon-192.png"
            }),
            type: "image/png",
            sizes: "192x192"
          },
          {
            src: InstanceRenderManager({
              instance: process.env.VITE_APP_INSTANCE,
              imex: "logo512.png",
              rome: "ro-favicon.png",
              promanager: "/pm/pm-icon-512.png"
            }),
            type: "image/png",
            sizes: "512x512"
          }
        ],
        theme_color: InstanceRenderManager({
          instance: process.env.VITE_APP_INSTANCE,
          imex: "#1890ff",
          rome: "#fff",
          promanager: "#1d69a6"
        }),
        background_color: "#fff",
        gcm_sender_id: "103953800507"
      }
    }),
    reactVirtualized(),
    react(),
    eslint(),
    // CompressionPlugin(), //Cloudfront already compresses assets, so not needed.
  ],
  define: {
    APP_VERSION: JSON.stringify(process.env.npm_package_version)
  },
  server: {
    host: true,
    port: 3000,
    open: true
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          antd: ["antd"],
          "react-redux": ["react-redux"],
          redux: ["redux"]
        }
      }
    }
  },
  optimizeDeps: {
    include: ["react", "react-dom", "antd", "@apollo/client", "@reduxjs/toolkit", "axios"],
    esbuildOptions: {
      loader: {
        ".js": "jsx"
      }
    }
  }
});
