import sucrase from "@rollup/plugin-sucrase";
import resolve from "@rollup/plugin-node-resolve";
import url from "rollup-plugin-url";
import builtins from 'rollup-plugin-node-builtins';
import multi from "@rollup/plugin-multi-entry";
import ts from "@wessberg/rollup-plugin-ts";
import commonjs from "@rollup/plugin-commonjs";
import ppostcss from "rollup-plugin-postcss";
import path from "path";

import postcss from "postcss";
import fs from "fs";
import importCss from "@atomico/rollup-plugin-import-css";
import workbox from "@atomico/rollup-plugin-workbox";
import sizes from "@atomico/rollup-plugin-sizes";
// import postcss from 'postcss';
import precss from "precss";
import autoprefixer from "autoprefixer";
import tailwindcss from "tailwindcss";
import inlineSvg from "postcss-inline-svg";

const sha256 = require("simple-sha256");

const postcssSVG = require("postcss-svg");

const files = fs.readdirSync("src/components");
const files1 = fs.readdirSync("src/hooks");

const dependencyTree = require("dependency-tree");
const md5File = require("md5-file");
const md5Hash = require("md5-hash");

const getCompFor = (name) => {
  const tree = dependencyTree.toList({
    filename: name,
    directory: "src",
    tsConfig: "tsconfig.json", // optional
    nodeModulesConfig: {
      entry: "module",
    }, // optional
    filter: (path) => path.indexOf("node_modules") === -1, // optional
    nonExistent: [], // optional
  });
  const list1 = tree.map((file) => md5File.sync(file)).join(",");
  const d = sha256.sync(list1);
  return d;
};

// kun-editor.
const getName = (item) => {
  if (item === "kun-editor") return `src/components/${item}/${item}.jsx`;
  return `src/components/${item}/${item}.tsx`;
};

const allFile = ["src/components/kun-editor/kun-editor.jsx"]
// const allFile = files1.concat(files).filter((ill) => !ill.startsWith(".")).map((item) => (item.endsWith("hook") ? `src/hooks/${item}/${item}.ts` : getName(item)));

const getHash = (allFile) => {
  const obj = allFile.map((file) => ({ [file]: getCompFor(file) })).reduce((p, c) => ({ ...p, ...c }));
  return obj;
};

const path1 = ".cache_1";

const checkEqual = (fileName, key, cacheObj) => {
  if (cacheObj[fileName] == null) return false;
  return cacheObj[fileName] === key;
};

const getP = () => {
  try {
    const cacheObj = JSON.parse(fs.readFileSync(path1, "utf8"));
    return cacheObj;
  } catch (e) {
    console.error(e);
    return {};
  }
};

const obj = getP();

const newFile = allFile.filter((file) => !checkEqual(file, getCompFor(file), obj));

fs.writeFileSync(path1, JSON.stringify(getHash(allFile)));

export default {
  input: newFile,
  external: [],
  // external: ["dayjs", "immer", "atomico", "@deckdeckgo/lazy-img", "@caedman/spring", "purify-ts", "funfix", "lazysizes",
  //   "@caedman/gs/dist/global-style",
  //   "@caedman/gs/dist/aync-hook",
  //   "purify-ts",
  //   "@caedman/gs",
  //   "toastr",
  //   "purify-ts/es/Maybe",
  //   "@caedman/kit/use-stylesheet"
  // ],
  output: {
    dir: "dist",
    format: "cjs",
    chunkFileNames: "chunks/[hash].js",
    sourcemap: false,
  },
  plugins: [
    builtins(),
    resolve({
      extensions: [".js", ".ts", ".tsx", ".svg", ".jsx", ".css"],
    }),
    commonjs(),
    // multi(),
    // ppostcss([
    //     postcssSVG({
    //       dirs: 'src/svgs'
    //     }),
    //   tailwindcss(),
    // plyr.css
    //   precss(),
    //   require("postcss-inline-svg")(),
    //   require("cssnano")(),
    // ]),
    url(),
    importCss({
      include: ["**/*.css", "**/*.scss", "../../node_modules/**/dist/**.css", "../../node_modules/**/**.css", "node_modules/plyr/**/**.css", "node_modules/plyr/**/*.css"],
      exclude: [],
      minimize: false, // will add the list of plugins cssnano
      // extensions: ['sass', 'scss'],
      /**
       * this function allows you to manipulate the return of the module
       * allowing, alter the export to be decorated by
       * other libraries
       */
      generate: async (code) => {
        const r = await postcss([
          inlineSvg({
            paths: ["src/svgs"],
          }),
          tailwindcss(), autoprefixer(), precss(),
          postcssSVG({
            dirs: "src/svgs",
          }),
        ]).process(code);
        return `export default ${JSON.stringify(r.toString())};`;
      },
    }),
    sucrase({
      include: ["src/**", "node_modules/plyr"],
      exclude: ["node_modules/**"],
      jsxPragma: "h",
      transforms: ["typescript", "jsx"],
    }),
  ],
};
