/*
 * ButtonsController.cpp
 *
 *  Created on: 14 nov. 2023
 *      Author: remi.heredero
 */

#include <board/ButtonsController.h>
#include "trace/trace.h"
#include "main.h"

ButtonsController::ButtonsController()
	: stCheckButtons(this),
	  stDebounce(this) {

	cbProvider = nullptr;
	cbMethod = nullptr;

	stInitial.addInitialTransition(&stCheckButtons);
	stCheckButtons.addTransition(event::evButtonIrq, &stDebounce);
	stCheckButtons.registerOnEntry((XFState::callback)&ButtonsController::fctCheckButtons);

	stDebounce.setTimeout(20, &stCheckButtons);
};

ButtonsController* ButtonsController::getInstance() {
	static ButtonsController buttonsController_;
	return &buttonsController_;
}

void ButtonsController::onIrq() {
	GEN(XFEvent(XFEvent::XFEventType::Event, event::evButtonIrq, this));
}

bool ButtonsController::registerCallback(
		interface::ButtonsControllerCallbackProvider *callbackProvider,
		interface::ButtonsControllerCallbackProvider::CallbackMethod callbackMethod) {

	if(callbackProvider == nullptr) return false;
	if(callbackMethod == nullptr) return false;

	cbProvider = callbackProvider;
	cbMethod = callbackMethod;

	return true;
}

void ButtonsController::fctCheckButtons() {
	if(cbProvider != nullptr) {

		newState[0] = HAL_GPIO_ReadPin(BUTTON0_GPIO_Port, BUTTON0_Pin);
		newState[1] = HAL_GPIO_ReadPin(BUTTON1_GPIO_Port, BUTTON1_Pin);
		newState[2] = HAL_GPIO_ReadPin(BUTTON2_GPIO_Port, BUTTON2_Pin);
		newState[3] = HAL_GPIO_ReadPin(BUTTON3_GPIO_Port, BUTTON3_Pin);

		if(newState[0] != buttonState[0]) {
			buttonState[0] = newState[0];
			(cbProvider->*cbMethod)(0, !buttonState[0]);

		}

		if(newState[1] != buttonState[1]) {
			buttonState[1] = newState[1];
			(cbProvider->*cbMethod)(1, !buttonState[1]);
		}

		if(newState[2] != buttonState[2]) {
			buttonState[2] = newState[2];
			(cbProvider->*cbMethod)(2, !buttonState[2]);
		}

		if(newState[3] != buttonState[3]) {
			buttonState[3] = newState[3];
			(cbProvider->*cbMethod)(3, !buttonState[3]);
		}

	}
}

