/**
 * Created by rockyl on 2019-03-28.
 */

const ts = require("typescript");
const fs = require('fs-extra');
const path = require('path');

let _options, _projectPath;

exports.prepare = function (tsconfig, projectPath) {
	const config = ts.parseJsonConfigFileContent(tsconfig, ts.sys, projectPath);
	_options = config.options;
	_projectPath = projectPath;
};

exports.compile = function (file, throwError = true) {
	if (!_options) {
		throw Error('no options input')
	}

	let filePath = path.resolve(_projectPath, file + (file.endsWith('.ts') ? '' : '.ts'));

	if (!fs.existsSync(filePath)) {
		filePath = path.resolve(_projectPath, file + '/index.ts');

		if (!fs.existsSync(filePath)) {
			if(throwError){
				throw new Error('source code file not exists');
			}
			return null;
		}
	}

	let source = fs.readFileSync(filePath, 'utf-8');
	let result = ts.transpileModule(source, {compilerOptions: _options});

	return {
		code: result.outputText,
		filePath,
		relativeFilePath: './' + path.relative(_projectPath, filePath),
	};
};
