import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import image from '@rollup/plugin-image';
import alias from '@rollup/plugin-alias';
import postcss from 'rollup-plugin-postcss-modules'
import babel from "rollup-plugin-babel";
import json from "rollup-plugin-json";
import autoprefixer from 'autoprefixer';
import postcssUrl from 'postcss-url';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import visualizer from 'rollup-plugin-visualizer';
import analyze from 'rollup-plugin-analyzer';
 

// import url from '@rollup/plugin-url';
// import less from "rollup-plugin-less";
import nodeEval from 'node-eval';

export function getModuleExports(moduleId) {
  const id = require.resolve(moduleId)
  const moduleOut = nodeEval(fs.readFileSync(id).toString(), id)
  let result = []
  const excludeExports = /^(default|__)/
  if (moduleOut && typeof moduleOut === 'object') {
      result = Object.keys(moduleOut)
          .filter(name => !excludeExports.test(name))
  }
  return result
}

export function getNamedExports(moduleIds) {
  const result = {}
  moduleIds.forEach( id => {
      result[id] = getModuleExports(id)
  })
  return result
}

const fs = require('fs');
const path = require('path');
const componentsFold = 'src/components';
const cModuleNames = fs.readdirSync(path.resolve(componentsFold));
const cModuleMap = cModuleNames.reduce((prev, name) => {
  const modulePath = `${componentsFold}/${name}`;
  prev[name] = `${modulePath}/index.ts`;
  const child = fs.readdirSync(path.resolve(modulePath));
  child.forEach(c => {
    const childFoldPath = `${modulePath}/${c}`;
    const isDir = fs.statSync(childFoldPath).isDirectory();
    if (isDir) {
      if (fs.existsSync(`${childFoldPath}/index.tsx`)) {
        prev[c] = `${childFoldPath}/index.tsx`;
      }
      if (c === 'Common' && fs.existsSync(childFoldPath) && fs.statSync(childFoldPath).isDirectory()) {
        const commonComponentsArr = fs.readdirSync(childFoldPath);
        commonComponentsArr.forEach(commonComponentFold => {
          const commonComponentFoldPath = `${childFoldPath}/${commonComponentFold}`;
          const isCommonComponentDir = fs.statSync(commonComponentFoldPath).isDirectory();
          if (isCommonComponentDir && fs.existsSync(`${commonComponentFoldPath}/index.tsx`)) {
            prev[`${commonComponentFold}`] = `${commonComponentFoldPath}/index.tsx`;
          }
        });
      }
    }
  });
  return prev;
}, {});

const extensions = ['.js', '.jsx', '.ts', '.tsx'];

export default {
  input: {
    '.': "src/lib-build.js",
    ...cModuleMap
  },
  output: [
    {
      dir: "lib",
      sourcemap: true,
      entryFileNames: '[name]/index.js',
      exports: 'named',
      // file: "lib/bundle.js",
      format: "cjs"
    },
    {
      dir: "eslib",
      sourcemap: true,
      entryFileNames: '[name]/index.js',
      exports: 'named',
      // file: "lib/bundle.js",
      format: "es"
    }
  ],
  plugins: [
    peerDepsExternal(),
    resolve({
      mainFields: ['jsnext'],
      preferBuiltins: true,
      browser: true,
      extensions,
    }),
    commonjs({
      include: 'node_modules/**',
      browser: true,
      namedExports: {
        ...getNamedExports([
          'prop-types',
          'draft-js',
        ]),
        'braft-extensions/dist/emoticon': ['defaultEmoticons']
      },
    }),
    babel({
      exclude: "node_modules/**",
      runtimeHelpers: true,
      extensions,
    }),
    image(),
    json(),
    // url(),
    // less(),
    postcss({
      extensions: ['.css', '.less'],
      plugins: [
        autoprefixer(),
        postcssUrl({
          url: 'inline'
        }),
      ],
      modules: true,
    }),
    alias({
      entries: [
        { find: '@', replacement: 'src' },
        { find: '@components', replacement: 'src/components' },
      ]
    }),
    visualizer({
      sourcemap: true,
      open: true,
    }),
    analyze(),
  ],
  onwarn: function(warning) {
    // Skip certain warnings
    // should intercept ... but doesn't in some rollup versions
    if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
    // console.warn everything else
    console.warn( warning.message );
  }
};
