/*
 * timemgt.c
 *
 *  Created on: Apr 28, 2021
 *      Author: Florian
 */

#include "timemgt.h"

/* Local static variables */
tTimeMgt_Channel Channels_tA[TIM_ChannelNumberMax_U8];


/* Functions */
void TimeMgt_Init (void)
{

}

void TimeMgt_Start (void)
{

}

void TimeMgt_Stop(void)
{
	uint8_t cnt = 0U;

	for (cnt=0U; cnt < TIM_ChannelNumberMax_U8; cnt++)
	{
		TimeMgt_DisableCyclicEvent(cnt);
		TimeMgt_RemoveCyclicEvent(cnt);
	}
}

void TimeMgt_AddCyclicEvent(uint8_t channel_u8, pTimeMgtCallback callback_p, uint32_t timeout_u32)
{
	if ((channel_u8 < TIM_ChannelNumberMax_U8) && (callback_p != NULL))
	{
		Channels_tA[channel_u8].callback_p = callback_p;
		Channels_tA[channel_u8].timeout_u32 = timeout_u32;
		Channels_tA[channel_u8].counter_u32 = 0U;
	}
}

void TimeMgt_RemoveCyclicEvent(uint8_t channel_u8)
{
	if ((channel_u8 < TIM_ChannelNumberMax_U8) && (Channels_tA[channel_u8].callback_p != NULL))
	{
		Channels_tA[channel_u8].callback_p = NULL;
		Channels_tA[channel_u8].timeout_u32 = 0U;
		Channels_tA[channel_u8].counter_u32 = 0U;
		Channels_tA[channel_u8].enable_b = FALSE;
	}
}

void TimeMgt_EnableCyclicEvent(uint8_t channel_u8)
{
	if (channel_u8 < TIM_ChannelNumberMax_U8)
	{
		if (Channels_tA[channel_u8].callback_p != NULL)
		{
			Channels_tA[channel_u8].enable_b = TRUE;
		}
	}
}

void TimeMgt_DisableCyclicEvent(uint8_t channel_u8)
{
	if (channel_u8 < TIM_ChannelNumberMax_U8)
	{
		Channels_tA[channel_u8].enable_b = FALSE;
	}
}

void TimeMgt_PeriodicFunction(void)
{
	uint8_t cnt;

	for (cnt=0U; cnt < TIM_ChannelNumberMax_U8; cnt++)
	{
		if (Channels_tA[cnt].enable_b == TRUE)
		{
			if (Channels_tA[cnt].counter_u32 < Channels_tA[cnt].timeout_u32)
			{
				Channels_tA[cnt].counter_u32++;
			}
			else
			{
				Channels_tA[cnt].counter_u32 = 0U;
				// Callback
				if (Channels_tA[cnt].callback_p != NULL)
				{
					Channels_tA[cnt].callback_p();
				}
			}

		}
	}

}
