import { join, dirname, extname, basename } from 'path';
import { readFileSync } from 'fs';
import nodeResolver from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import json from '@rollup/plugin-json';
import image from '@rollup/plugin-image';
import clear from 'rollup-plugin-clear';
import progress from 'rollup-plugin-progress';
import externals from 'rollup-plugin-node-externals';
import typescript from 'rollup-plugin-typescript2';
import { terser } from 'rollup-plugin-terser';
import copy from 'rollup-plugin-copy';
import visualizer from 'rollup-plugin-visualizer';
import postcss from 'rollup-plugin-postcss';
import babel from 'rollup-plugin-babel';
// import transformTaggedTemplate from '@ywfe/rollup-plugin-styled-components';
import lessToJS from 'less-vars-to-js';

import pkg from './package.json';

const antdVariables = lessToJS(
  readFileSync(join(__dirname, './node_modules/antd/es/style/themes/default.less'), 'utf8'),
);
const customVariables = lessToJS(
  readFileSync(join(__dirname, './components/styles/antd-theme.less'), 'utf8'),
  {
    resolveVariables: true,
    stripPrefix: true,
  },
);

const themeVariables = {
  ...antdVariables,
  ...customVariables,
};

const isProd = process.env.NODE_ENV === 'production';
const extensions = ['.js', '.jsx', '.ts', '.tsx'];

const formats = {
  commonjs: {
    format: 'cjs',
    file: pkg.main,
    sourcemap: true,
    exports: 'named',
  },
  esm: {
    format: 'esm',
    file: pkg.module,
    sourcemap: true,
    exports: 'named',
  },
  umd: {
    format: 'umd',
    name: pkg.name,
    sourcemap: true,
    exports: 'named',
    globals: {
      antd: 'antd',
      react: 'React',
      'react-dom': 'ReactDOM',
      'react-is': 'ReactIs',
      'prop-types': 'PropTypes',
      'react-router-dom': 'ReactRouterDOM',
      'styled-components': 'styled',
    },
  },
};

const config = {
  input: './components/index.ts',
  inlineDynamicImports: true,
  output: [formats.esm, formats.commonjs],
  plugins: [
    clear({
      targets: ['lib'],
    }),
    progress({
      clearLine: false,
    }),
    replace({
      __THEM_PATH_: "'~@ywfe/ywd/lib/styles/antd-theme.less'",
    }),
    externals({
      deps: true,
    }),
    nodeResolver(),
    typescript(),
    image(),
    json(),
    postcss({
      use: [
        [
          'less',
          {
            javascriptEnabled: true,
          },
        ],
      ],
      plugins: [],
    }),
    copy({
      targets: [{ src: 'components/styles/**/*', dest: 'lib/styles/' }],
    }),
    babel({
      plugins: [
        ['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }],
        ['@babel/plugin-proposal-decorators', { legacy: true }],
        [
          'styless',
          {
            import: '~antd/lib/style/themes/default.less',
            lessOptions: {
              javascriptEnabled: true,
            },
          },
        ],
      ],
    }),
    // transformTaggedTemplate({
    //   parserOptions: {
    //     presets: ["es2015"],
    //     allowImportExportEverywhere: true,
    //     styless: [
    //       {
    //         import: '~antd/lib/style/themes/default.less',
    //         lessOptions: {
    //           javascriptEnabled: true,
    //         },
    //       },
    //       {
    //         import: './components/styles/antd-theme.less',
    //         lessOptions: {
    //           javascriptEnabled: true,
    //         },
    //       },
    //     ]
    //   },
    //   tagsToProcess: ['styled'],
    // }),
  ],
  watch: {
    include: 'components/**',
    exclude: 'node_modules/**',
  },
};

if (isProd) {
  const file = formats.commonjs.file;
  const ext = extname(file);

  config.output.push({
    ...formats.umd,
    file: join(dirname(file), `${basename(file, ext)}.umd${ext}`),
    plugins: [],
  });

  config.plugins.push(
    visualizer({
      title: `${pkg.name} - ${pkg.author.name}`,
      filename: 'lib/bundle-analyzer-report.html',
    }),
  );

  config.output.push({
    ...formats.umd,
    file: join(dirname(file), `${basename(file, ext)}.umd.min${ext}`),
    plugins: [terser()],
  });
}

export default config;
