/*
 * ButtonStateSm.cpp
 *
 *  Created on: 19 nov. 2023
 *      Author: remi.heredero
 */

#include <button/ButtonStateSm.h>
#include "mdw/button/ButtonEventsHandler.h"

//TODO start State Machine. For that, turn ButtonEventsHandler to a State Machine (Initial, run)
ButtonStateSm::ButtonStateSm()
	: buttonIndex_(getNbInstance()) {
	currentState_ = state::initial;
}

uint8_t ButtonStateSm::getNbInstance(){
	static uint8_t nbInstances = 0;
	return nbInstances++;
}

void ButtonStateSm::genButtonPressed() {
	GEN(XFEvent(XFEvent::Event, event::evButtonPressed, this));
}
void ButtonStateSm::genButtonReleased() {
	GEN(XFEvent(XFEvent::Event, event::evButtonReleased, this));
}

XFEventStatus ButtonStateSm::processEvent() {
	eEventStatus eventStatus = XFEventStatus::Unknown;

	const XFEvent* ev = getCurrentEvent();
	XFEvent::XFEventType evType = ev->getEventType();
	int evid = ev->getId();

	oldState_ = currentState_;
	changeState_ = false;

	switch (currentState_) {
		case state::initial:
			if(evType == XFEvent::Initial) {
				currentState_ = state::waitButtonPressed;
				changeState_ = true;
				eventStatus = XFEventStatus::Consumed;
			}
			break;

		case state::waitButtonPressed:
			if(evid == event::evButtonPressed) {
				currentState_ = state::buttonPressed;
				changeState_ = true;
				eventStatus = XFEventStatus::Consumed;
				scheduleTimeout(event::evTimeout, 1000);
			}
			break;

		case state::buttonPressed:
			if(evid == event::evButtonReleased) {
				currentState_ = state::buttonShortPressed;
				changeState_ = true;
				eventStatus = XFEventStatus::Consumed;
				unscheduleTimeout(event::evTimeout);
			}
			if(evid == event::evTimeout) {
				currentState_ = state::buttonLongPressed;
				changeState_ = true;
				eventStatus = XFEventStatus::Consumed;
			}
			GEN(XFNullTransition(this));
			break;

		case state::buttonShortPressed:
			if(evType == XFEvent::XFEventType::NullTransition) {
				currentState_ = state::waitButtonPressed;
				changeState_ = true;
				eventStatus = XFEventStatus::Consumed;
			}
			break;

		case state::buttonLongPressed:
			if(evType == XFEvent::XFEventType::NullTransition) {
				currentState_ = state::waitButtonPressed;
				changeState_ = true;
				eventStatus = XFEventStatus::Consumed;
			}
			break;
	}

	if(changeState_) {
		switch (oldState_) { // onExit
			case state::initial:
				break;

			case state::waitButtonPressed:
				break;

			case state::buttonPressed:
				break;

			case state::buttonShortPressed:
				break;

			case state::buttonLongPressed:
				break;
		}

		switch (currentState_) {
			case state::initial:
				break;

			case state::waitButtonPressed:
				break;

			case state::buttonPressed:
				break;

			case state::buttonShortPressed:
				ButtonEventsHandler::getInstance()->notifyButtonShortPressed(buttonIndex_);
				break;

			case state::buttonLongPressed:
				ButtonEventsHandler::getInstance()->notifyButtonLongPressed(buttonIndex_);
				break;
		}
	}
	return eventStatus;
}
