/*
 * EXTIHandler_STM32.cpp
 *
 *  Created on: Feb 24, 2024
 *      Author: gabriel
 */

#include "EXTIHandler_STM32.hpp"

EXTIHandler_STM32 extiHandlerStm32Singleton;

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin){
	extiHandlerStm32Singleton.callback(GPIO_Pin);
}

EXTIHandler_STM32::EXTIHandler_STM32(){
	singletonPointer = &extiHandlerStm32Singleton;
}

int32_t EXTIHandler_STM32::registerCallback(
		std::function<void(void*)> callbackFunction, void* argument, GPIO_Pin* irqPin) {
	uint8_t pinNumber = ((GPIO_Pin_STM32*)irqPin)->getPin();
	functionArray[pinNumber] = callbackFunction;
	argumentArray[pinNumber] = argument;
	return 0;
}

int32_t EXTIHandler_STM32::setCallbackEnabled(GPIO_Pin *irqPin, bool enabled) {
	uint8_t pinNumber = ((GPIO_Pin_STM32*)irqPin)->getPin();
	enabledArray[pinNumber] = enabled;
	return 0;
}

void EXTIHandler_STM32::callback(uint16_t GPIO_Pin) {
	uint8_t pinNumber = gpioPinToPinNumber(GPIO_Pin);
	if(enabledArray[pinNumber]){
		functionArray[pinNumber](argumentArray[pinNumber]);
	}
}

uint8_t EXTIHandler_STM32::gpioPinToPinNumber(uint16_t 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;
	}
}
