import path from 'path';
import glob from 'glob';
import babel from 'rollup-plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import resolve from '@rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';
import visualizer from 'rollup-plugin-visualizer';

const getConf = (input, output, name) => ({
  input: `src/react/${input}`,
  output: {
    name: `saagie-ui${name ? `-${name}` : ''}`,
    file: `react/${output}`,
    format: 'umd',
    globals: {
      'formsy-react': 'Formsy',
      'prop-types': 'PropTypes',
      react: 'React',
      'react-dom': 'ReactDOM',
    },
  },
  external: [
    'formsy-react',
    'prop-types',
    'react',
    'react-dom',
  ],
  plugins: [
    resolve(),
    json({
      include: 'src/**',
      compact: true,
    }),
    babel({
      exclude: 'node_modules/**',
      runtimeHelpers: true,
    }),
    commonjs({
      namedExports: {
        'node_modules/react-is/index.js': ['isValidElementType', 'isContextConsumer'],
      },
    }),
    visualizer({
      filename: `./.stats/react-${name || 'core'}.html`,
      title: `${name || 'core'} Bundle`,
    }),
    terser(),
  ],
});

const conf = glob.sync('src/react/*.js').map((file) => {
  const input = path.basename(file);
  const isCore = input === 'core.js';
  const output = isCore ? 'index.js' : input;
  const name = isCore ? null : path.parse(input).name;

  return getConf(input, output, name);
});

export default conf;
