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

const {compile} = require('./rollup-compiler');
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const watchr = require('watchr');
const program = require('commander');

program
	.option('-s, --source [string]', 'Source path')
	.option('-o, --output [string]', 'Output path', 'dist/customs')
	.option('-w, --watch', 'Auto build', false)
	.option('-p, --prod', 'Pack with production env', false)
	.parse(process.argv);

(async function () {
	if (program.source) {
		await watchWrapper(program.source, program.output);
	} else {
		const files = glob.sync('*', {cwd: process.cwd() + '/src/custom'});
		for (let file of files) {
			await compileProcess(file, program.output);
		}
	}

	console.log('complete!');
})();

async function watchWrapper(sourcePath, output) {
	if (program.watch) {
		let srcPath = 'src/custom/' + sourcePath + '/src';
		let stalker = watchr.open(srcPath, function (changeType, fullPath, currentStat, previousStat) {
			console.log('watch:', fullPath);
			compileProcess(sourcePath, output)
		}, next);
		stalker.setConfig({
			interval: 100,
		});
		compileProcess(sourcePath, output)
	} else {
		await compileProcess(sourcePath, program.output)
	}
}

function next(err) {
	if (err) return console.log('watch failed on', path, 'with error', err);
}

async function compileProcess(id, output) {
	const meta = fs.readJsonSync(path.join('src/custom/' + id, 'meta.json'));
	const result = await compile('src/custom/' + id + '/src/index.ts', {
		prod: program.prod,
		moduleName: id,
	});
	meta.id = id;
	let code;
	if (result) {
		code = result.code;
		meta.code = result.code;
	}

	const outputPath = path.join(output, id);
	console.log(outputPath);
	fs.ensureDirSync(path.dirname(outputPath));
	fs.writeJsonSync(outputPath + '.json', meta, {spaces: '  '});

	let debugOutputPath = 'src/custom/' + id + '/debug/main';
	if (result && result.map) {
		fs.writeFileSync(debugOutputPath + '.js.map', result.map.toString());
		code += `\n//# sourceMappingURL=` + 'main' + '.js.map';
	}
	fs.writeFileSync(debugOutputPath + '.js', code);
	/*fs.writeJsonSync(outputPath + '-req.json', {
		data: JSON.stringify(meta)
	});*/

	console.log(`compile custom [${id}] successfully!`);
}
