//#define ASCRIPT_DLL_MODULE
//-----------------------------------------------------------------------------
// AScript sys module
//-----------------------------------------------------------------------------
#include "Module_sys.h"

AScript_BeginModule(sys)

// sys.echo()
AScript_DeclareFunction(echo)
{
	DeclareArg(env, _T("flag"), VTYPE_Boolean);
}

AScript_ImplementFunction(echo)
{
	env.SetEchoFlag(context.GetBoolean(0));
	return Value::Null;
}

// sys.exit(status?:number)
AScript_DeclareFunction(exit)
{
	DeclareArg(env, _T("status"), VTYPE_Number, false, OCCUR_ZeroOrOnce);
}

AScript_ImplementFunction(exit)
{
	::exit(context.IsNumber(0)? static_cast<int>(context.GetNumber(0)) : 0);
	return Value::Null;
}

AScript_ModuleEntry()
{
	do {
		Value value;
		ValueList &valList = value.InitAsList(env);
		valList.push_back(Value(env, _T(".")));
		valList.push_back(Value(env, File::GetBaseDir().c_str()));
		do {
			String dirName(File::GetBaseDir());
			dirName += File::Separator;
			dirName += _T("DLLs");
			valList.push_back(Value(env, dirName.c_str()));
		} while (0);
		do {
			String dirName(File::GetBaseDir());
			dirName += File::Separator;
			dirName += _T("Lib");
			valList.push_back(Value(env, dirName.c_str()));
		} while (0);
		const TCHAR *str = ::_tgetenv(_T("ASCRIPTPATH"));
		if (str != NULL) {
			SplitPathList(env, str, valList);
		}
		env.AssignValue(Symbol::Add(_T("path")), value, false);
	} while (0);
	do {
		Value value;
		value.InitAsFile(env)->GetFile().OpenStdin();
		env.AssignValue(Symbol::Add(_T("stdin")), value, false);
	} while (0);
	do {
		Value value;
		value.InitAsFile(env)->GetFile().OpenStdout();
		env.AssignValue(Symbol::Add(_T("stdout")), value, false);
	} while (0);
	do {
		Value value;
		value.InitAsFile(env)->GetFile().OpenStderr();
		env.AssignValue(Symbol::Add(_T("stderr")), value, false);
	} while (0);
	AScript_AssignValue(Symbol::Add(_T("ps1")), Value(env, _T(">>> ")));
	AScript_AssignValue(Symbol::Add(_T("ps2")), Value(env, _T("... ")));
	AScript_AssignFunction(echo);
	AScript_AssignFunction(exit);
}

void Setup(Module *pModule, Signal sig, int argc, const TCHAR *argv[])
{
	Value value;
	ValueList &valList = value.InitAsList(*pModule);
	if (argc > 1) {
		valList.push_back(Value(*pModule, File::MakeAbsPath(argv[1], NULL).c_str()));
		for (int i = 2; i < argc; i++) {
			valList.push_back(Value(*pModule, argv[i]));
		}
	}
	pModule->AssignValue(Symbol::Add(_T("argv")), value, false);
}

AScript_EndModule(sys)

AScript_DLLModuleEntry(sys)
