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

#include <button/ButtonEventsHandler.h>
#include "trace/trace.h"
#include "board/ButtonsController.h"


ButtonEventsHandler::ButtonEventsHandler()
	: stRun(this) {
	for(uint8_t i = 0; i< MAX_OBSERVER; i++) {
		observer_[i] = nullptr;
	}

	stInitial.setNextState(&stRun);
	stRun.registerOnEntry((XFState::callback)&ButtonEventsHandler::startButtonSM);

}

void ButtonEventsHandler::startButtonSM(const XFEvent* ev) {
	buttonStateSm_[0].startBehavior();
	buttonStateSm_[1].startBehavior();
	buttonStateSm_[2].startBehavior();
	buttonStateSm_[3].startBehavior();
}

ButtonEventsHandler* ButtonEventsHandler::getInstance() {
	static ButtonEventsHandler buttonEventsHandler_;
	return &buttonEventsHandler_;
}

void ButtonEventsHandler::onButtonChangeState(uint16_t buttonIndex, bool pressed) {
	if(pressed) {
		buttonStateSm_[buttonIndex].genButtonPressed();
	} else {
		buttonStateSm_[buttonIndex].genButtonReleased();
	}
}

bool ButtonEventsHandler::subscribe(interface::ButtonEventsHandlerObserver *observer) {
	for(uint8_t i = 0; i < MAX_OBSERVER; i++) {
		if (observer_[i] == nullptr) {
			observer_[i] = observer;
			return true;
		}
	}
	return false;
}

void ButtonEventsHandler::unsubscribe(interface::ButtonEventsHandlerObserver *observer) {
	for(uint8_t i = 0; i < MAX_OBSERVER; i++) {
			if (observer_[i] == observer) {
				observer_[i] = nullptr;
			}
		}
}

void ButtonEventsHandler::notifyButtonShortPressed(ButtonIndex buttonIndex) {
	for(uint8_t i = 0; i < MAX_OBSERVER; i++) {
		if (observer_[i] != nullptr) {
			observer_[i]->onButtonShortPressed(buttonIndex);
		}
	}
}

void ButtonEventsHandler::notifyButtonLongPressed(ButtonIndex buttonIndex) {
	for(uint8_t i = 0; i < MAX_OBSERVER; i++) {
		if (observer_[i] != nullptr) {
			observer_[i]->onButtonLongPressed(buttonIndex);
		}
	}
}
