/**
 * 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/scripts'] = process.argv;

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

console.log('complete!');

function compileProcess(sourcePath, output) {
	const id = sourcePath;
	const meta = fs.readJsonSync(path.join('src/script/' + sourcePath, 'meta.json'));
	const result = compile('src/script/' + sourcePath, false);
	meta.id = id;
	if(result){
		meta.code = result.code;
	}

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

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