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

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

ButtonStateSm::ButtonStateSm()
	: buttonIndex_(getNbInstance()),
	  stWaitButtonPressed(this),
	  stButtonPressed(this),
	  stButtonShortPressed(this),
	  stButtonLongPressed(this) {

	stInitial.addInitialTransition(&stWaitButtonPressed);

	stWaitButtonPressed.addTransition(event::evButtonPressed, &stButtonPressed);

	stButtonPressed.setTimeout(1000, &stButtonLongPressed);
	stButtonPressed.addTransition(event::evButtonReleased, &stButtonShortPressed);
	stButtonPressed.registerOnExit((XFState::callback)&ButtonStateSm::genNullTransition);

	stButtonShortPressed.registerOnEntry((XFState::callback)&ButtonStateSm::notifyShortPress);
	stButtonShortPressed.addTransition(event::evReturn, &stWaitButtonPressed);

	stButtonLongPressed.registerOnEntry((XFState::callback)&ButtonStateSm::notifyLongPress);
	stButtonLongPressed.addTransition(event::evReturn, &stWaitButtonPressed);
}

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));
}

void ButtonStateSm::notifyShortPress() {
	ButtonEventsHandler::getInstance()->notifyButtonShortPressed(buttonIndex_);
}

void ButtonStateSm::notifyLongPress() {
	ButtonEventsHandler::getInstance()->notifyButtonLongPressed(buttonIndex_);
}

void ButtonStateSm::genNullTransition() {
	GEN(XFEvent(XFEvent::Event, event::evReturn, this));
}
