#include "bsp_event.h"

#include "kit_data.h"
#include "kit_debug.h"


kit_ret_e bsp_event_register(EventItem *item, uint32_t enable_dly, uint32_t disable_dly, EventCall call)
{
    kit_ret_e res = kKit_Ret_ParamErr;
	EventParamArrary *param_arr;
    KIT_ASSERT_PARAM((item != NULL) && (call != NULL));
    
	if((item != NULL) && (call != NULL) && (item->cur_cnt < item->cnt))
	{
		param_arr = &item->param_arr[item->cur_cnt];
		param_arr->pre_call = call;
		param_arr->enable_dly = enable_dly;
		param_arr->disable_dly = disable_dly;
		item->cur_cnt++;
        res = kKit_Ret_Ok;
	}
    return res;
}



void bsp_event_poll(EventItem *item, uint16_t base_time)
{
    uint32_t i;
    EventParamArrary *param;
    KIT_ASSERT_PARAM(item != NULL);
    KIT_ASSERT_PARAM(base_time > 0);
        
    if(item != NULL)
    {
        for(i = 0; i < item->cnt; i++)
        {                
            param = &item->param_arr[i];
            if((param->pre_call != NULL) && (param->enable_dly != 0))
            {                
                param->pre_call(item, i);
                if(KIT_GET_BIT_32(item->flag, i) != 0)
                {
                    if(item->disable_cond == true)
                    {
                        param->tick += base_time;
                        if(param->tick >= param->disable_dly)
                        {
                            KIT_CLR_BIT_32(item->flag, i);
                            param->tick = 0;
                        }                
                    }
                    else
                    {
                        param->tick = 0;
                    }
                }
                else
                {
                    if(item->enable_cond == true)
                    {
                        param->tick += base_time;
                        if(param->tick >= param->enable_dly)
                        {
                            KIT_SET_BIT_MASK_32(item->flag, i);
                            param->tick = 0;
                        }                
                    }
                    else
                    {
                        param->tick = 0;
                    }
                }
            }
        }
    }
}
