/*
 * XFState.cpp
 *
 *  Created on: 23 nov. 2023
 *      Author: remi.heredero
 */

#include "xf/XFState.h"
#include "xf/include/xf/behavior.h"
#include <cassert>
#include "xf/event.h"
#include "trace/trace.h"

XFState::XFState(XFBehavior* behavior)
	: pBehavior(behavior) {
	assert(behavior != nullptr);
	cbState_ = nullptr;
	cbEntry_ = nullptr;
	cbExit_ = nullptr;
	cbEvState_ = nullptr;
	cbEvEntry_ = nullptr;
	cbEvExit_ = nullptr;
}

void XFState::addTransition(XFEvent::XFEventType type, const int evid, const int time, XFState* state) {
	assert(state != nullptr);
	transition t;
	t.evid = evid;
	t.time = time;
	t.evType = type;
	t.nextState = state;
	transitions_.push_back(t);
}

XFEventStatus XFState::changeState(XFState* state) {
	pBehavior->curentXFState_ = state;
	pBehavior->changeXFState = true;
	return XFEventStatus::Consumed;
}

XFEventStatus XFState::onState(const XFEvent* ev) {

	if(cbState_ != nullptr) {
		(pBehavior->*cbState_)();
	}
	if(cbEvState_ != nullptr) {
		(pBehavior->*cbEvState_)(ev);
	}

	for(transition t : transitions_) {

		switch(ev->getEventType()) {

			case XFEvent::XFEventType::Initial:
				if(t.evType == XFEvent::XFEventType::Initial) {
					return changeState(t.nextState);
				}
				break;

			case XFEvent::XFEventType::Timeout:
				if(t.evType == XFEvent::XFEventType::Timeout) {
					return changeState(t.nextState);
				}
				break;

			case XFEvent::XFEventType::Event:
				if(t.evid == ev->getId()) {
					return changeState(t.nextState);
				}
				break;

		}


	}

	return XFEventStatus::NotConsumed;
}

void XFState::onEntry(const XFEvent* ev) {
	if(cbEntry_ != nullptr) {
		(pBehavior->*cbEntry_)();
	}

	if(cbEvEntry_ != nullptr) {
		(pBehavior->*cbEvEntry_)(ev);
	}

	for(transition t : transitions_) {

		if(t.evType == XFEvent::XFEventType::Timeout) {
			pBehavior->scheduleTimeout(XFEvent::Timeout, t.time);
		}

	}
}
void XFState::onExit(const XFEvent* ev) {
	if(cbExit_ != nullptr) {
		(pBehavior->*cbExit_)();
	}

	if(cbEvExit_ != nullptr) {
		(pBehavior->*cbEvExit_)(ev);
	}

	for(transition t: transitions_) {

		if(t.evType == XFEvent::XFEventType::Timeout) {
			if(ev->getEventType() != XFEvent::XFEventType::Timeout) {
				pBehavior->unscheduleTimeout(XFEvent::Timeout);
			}
		}
	}
}
