// __author__ = Juan Carlos De Abreu (jcabreur@gmail.com)

#include "DataTime.h"
#include "../DataTypes/DataInt.h"

BEGIN_TEG_NAMESPACE();

DataTime::DataTime(const std::vector<SmartPointer<IData> >& params)
	: IData(DATA_TIME) {
	// 
	const SmartPointer<DataInt> interval_ = castToInt(params[0]);
	const SmartPointer<DataInt> duration_ = castToInt(params[1]);
	
	used = 0;
	begin = last = clock();
	interval = interval_->value;
	end = duration_->value;
	isRunning = true;

	// Por ahora voy asumir que las funciones que se llaman son sin parametros
	funcInterval = castToDataCallFunction(params[2]);
	funcEnd = castToDataCallFunction(params[3]);
}

DataTime::~DataTime() {
	funcInterval = NULL;
	funcEnd = NULL;
}

// Method to pause the time.
void DataTime::pause(void) {
	used = clock() - begin;
	isRunning = false;
}

// Method to stop the time.
void DataTime::stop(void) {
	used = 0;
	isRunning = false;
}

// Method to start the time.
void DataTime::start(void) {
	const clock_t clk = clock();
	begin = clk - used;
	last = clk - used % interval;
	isRunning = true;
}

// For . operator
SmartPointer<IData> DataTime::getMethod(SmartPointer<IData> elem, std::map<std::string, SmartPointer<IData>>& variables) {
	// Check if the elem is a method call.
	if (elem->type != DATA_CALL_FUNCTION) return NULL;
	SmartPointer<DataCallFunction> method = castToDataCallFunction(elem);
	std::vector<SmartPointer<IData>> params;
	const int nParams = static_cast<int> (method->param.size());
	for (int i = 0; i < nParams; ++i) {
		params.push_back(method->param[i]->resolve(variables));
	}

	if (params.size() == 0 && method->name == _T("start")) {
		start(); return NULL;
	}
	if (params.size() == 0 && method->name == _T("stop")) {
		stop();	return NULL;
	}
	if (params.size() == 0 && method->name == _T("pause")) {
		pause(); return NULL;
	}

	PRINT_LOG(TYPE_ERROR, _T("Invalid method '%s' or incorrect number for parameters for a Timer var"));
	return NULL;
}

END_TEG_NAMESPACE();
