/*
 * EXTIHandler_STM32.cpp
 *
 *  Created on: Apr 20, 2024
 *      Author: Gabriel
 */

#include "EXTIHandler_STM32.hpp"

/*
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin){
	EXTIHandler_STM32::EXTI_Callback(GPIO_Pin);
}
*/

EXTIHandler_STM32::EXTIHandler_STM32() {

}

EXTIHandler_STM32::~EXTIHandler_STM32() {

}

void EXTIHandler_STM32::EXTI_Callback(uint16_t GPIO_Pin){
	// TODO Protect array with mutex
	EXTIHandler_STM32* object = objects[gpioPinToPinNumber(GPIO_Pin)];
	if(object){
		object->irqHandler(nullptr);
	}
}

int32_t EXTIHandler_STM32::registerCallback(GPIO_Pin_STM32* pin){
	// TODO Protect array with mutex
	int8_t pinNumber = gpioPinToPinNumber(pin->getPin());
	if(!objects[pinNumber]){
		objects[pinNumber] = this;
		return 0;
	}else{
		// Already enabled
		return -1;
	}
}

int32_t EXTIHandler_STM32::deregisterCallback(GPIO_Pin_STM32* pin){
	// TODO Protect array with mutex
	int8_t pinNumber = gpioPinToPinNumber(pin->getPin());
	if(objects[pinNumber]){
		objects[pinNumber] = nullptr;
		return 0;
	}else{
		return -1;
	}
}

int8_t EXTIHandler_STM32::gpioPinToPinNumber(uint16_t GPIO_Pin) {
	assert_param(IS_GPIO_PIN(GPIO_Pin));
	switch(GPIO_Pin){
	case GPIO_PIN_0:
		return 0;
	case GPIO_PIN_1:
		return 1;
	case GPIO_PIN_2:
		return 2;
	case GPIO_PIN_3:
		return 3;
	case GPIO_PIN_4:
		return 4;
	case GPIO_PIN_5:
		return 5;
	case GPIO_PIN_6:
		return 6;
	case GPIO_PIN_7:
		return 7;
	case GPIO_PIN_8:
		return 8;
	case GPIO_PIN_9:
		return 9;
	case GPIO_PIN_10:
		return 10;
	case GPIO_PIN_11:
		return 11;
	case GPIO_PIN_12:
		return 12;
	case GPIO_PIN_13:
		return 13;
	case GPIO_PIN_14:
		return 14;
	case GPIO_PIN_15:
		return 15;
	}
	// TODO implement error handling here
	return -1;
}
