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

const {prepare, compile} = require('./tscompiler');
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');

const tsconfig = fs.readJsonSync('tsconfig.json');
prepare(tsconfig, process.cwd());

const [_, __, sourcePath, outputPath = 'dist/processes', builtin] = process.argv;

const isBuiltin = builtin ? builtin === 'builtin' : true;
if (sourcePath) {
	if(sourcePath.includes('/')){
		compileProcess(sourcePath, outputPath, isBuiltin);
	}else{
		const files = glob.sync(sourcePath + '/*', {cwd: process.cwd() + '/src/process'});
		for (let file of files) {
			compileProcess(file, outputPath, isBuiltin);
		}
	}
} else {
	const files = glob.sync('*/*', {cwd: process.cwd() + '/src/process'});
	for (let file of files) {
		compileProcess(file, outputPath, isBuiltin);
	}
}

console.log('complete!');

function compileProcess(sourcePath, output, isBuiltin) {
	const arr = sourcePath.split('/');
	const group = arr[0];
	const id = arr[1];
	const meta = fs.readJsonSync(path.join('src/process/' + sourcePath, 'meta.json'));
	const result = compile('src/process/' + sourcePath, false);
	meta.id = id;
	if(result){
		meta.script = result.code;
	}
	meta.group = group;
	if(isBuiltin){
		meta.type = 'builtin'
	}

	const outputPath = path.join(output, sourcePath);
	fs.ensureDirSync(path.dirname(outputPath));
	fs.writeJsonSync(outputPath + '.json', meta, {spaces: '  '});
	//fs.writeFileSync(outputPath + '.js', code);

	console.log(`compile process [${sourcePath}] successfully!`);
}
