/**
 * Created by rockyl on 2019-11-22.
 */

const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const progress = require('rollup-plugin-progress');
const typescript = require('rollup-plugin-typescript');
const {uglify} = require('rollup-plugin-uglify');
const rollup = require('rollup');

let cache;

exports.compile = async function (file, options) {
	const {prod = false, moduleName} = options;

	let plugins = [
		progress(),
		resolve({
			//only: [/^\.{0,2}\//],
		}),
		typescript({
			//useTsconfigDeclarationDir: true,
		}),
		commonjs(),
	];

	if (prod) {
		plugins.push(uglify({}));
	}

	let writeConfig = {
		format: prod ? 'cjs' : 'umd',
		name: moduleName,
		sourcemap: !prod,
		globals: {
			tslib: 'tslib'
		},
	};

	const bundle = await buildWithCache();
	const {output: [result]} = await bundle.generate(writeConfig);
	return result;

	async function buildWithCache() {
		const bundle = await rollup.rollup({
			input: file,
			plugins,
			onwarn: warning => {
				console.log(warning);
			},
			external: ['tslib'],
			cache,
		});
		cache = bundle.cache;
		return bundle;
	}
};
