#include "Signal.h"
#include "Symbol.h"
#include "Value.h"
#include "Expr.h"

namespace AScript {

//-----------------------------------------------------------------------------
// Signal
//-----------------------------------------------------------------------------
Signal::Signal() : _pMsg(new Message()), _stackLevel(0)
{
}

Signal::Signal(const Signal &sig) :
						_pMsg(sig._pMsg), _stackLevel(sig._stackLevel + 1)
{
	if (_stackLevel > MAX_STACK_LEVEL) {
		SetError(ERR_SystemError, _T("stack level exceeds maximum (%d)"), MAX_STACK_LEVEL);
	}
}

Signal::Message::Message() : sigType(SIGTYPE_None),
	errType(ERR_None), errTypeSaved(ERR_None), pExprCause(NULL), pValue(new Value())
{
}

String Signal::GetErrString() const
{
	String str;
	const Expr *pExprCause = GetExprCause();
	if (pExprCause != NULL) {
		TCHAR buff[32];
		::_stprintf(buff, _T("%d "), pExprCause->GetLineNo());
		str += buff;
	}
	str += GetErrorName();
	str += _T(": ");
	str += _pMsg->str.c_str();
	return str;
}

void Signal::SetError(ErrorType errType, const TCHAR *format, ...)
{
	va_list list;
	va_start(list, format);
	SetErrorV(errType, format, list);
	va_end(list);
}

void Signal::SetErrorV(ErrorType errType,
					const TCHAR *format, va_list list, const TCHAR *textPre)
{
	TCHAR str[2048];
	::_tcscpy(str, textPre);
	::_vstprintf(str + ::_tcslen(textPre), format, list);
	_pMsg->sigType = SIGTYPE_Error;
	_pMsg->errType = errType;
	_pMsg->str = str;
	*_pMsg->pValue = Value::Null;
}

}
