#include "TimeCtrl.h"
#include "../App_Headers/includes.h"
typedef struct{
    unsigned int Time;
    unsigned char En;
}s_TimeCtrl;
s_TimeCtrl TimeCtrl[TimeSNMax];

typedef struct{
    unsigned int Timer_2ms;
    unsigned int Timer_10ms;
}s_BaseTimer;
s_BaseTimer BaseTimer;


/*************************************************************************
 * Timer Control
*************************************************************************/
void InitTimeCtrl(void){
    unsigned char i;

    for(i = 0; i < TimeSNMax; i++){
        TimeCtrl[i].Time = 0;
        TimeCtrl[i].En = 0;
    }

    BaseTimer.Timer_2ms = 0;
    BaseTimer.Timer_10ms = 0;
}

void TimerCtrlms(unsigned int time){
    unsigned char i;

    for(i = 0; i < TimeSNMax; i++){
        if(TimeCtrl[i].En){
            if(TimeCtrl[i].Time < MAX_CTRL_TIME){
                TimeCtrl[i].Time += time;
            }
        }else{
            TimeCtrl[i].Time = 0;
        }
    }
}

void EnableTimeCtrl(e_TimeSN sn){
    if(!TimeCtrl[sn].En){
        TimeCtrl[sn].En = 1;
        TimeCtrl[sn].Time = 0;
    }
}

void DisableTimeCtrl(e_TimeSN sn){
    if(TimeCtrl[sn].En){
        TimeCtrl[sn].En = 0;
        TimeCtrl[sn].Time = 0;
    }
}

void ClearCtrlTime(e_TimeSN sn){
    TimeCtrl[sn].Time = 0;
}

unsigned int GetCtrlTime(e_TimeSN sn){
    return TimeCtrl[sn].Time;
}

/*************************************************************************
 * Timer Task
 * 2ms / 10ms
*************************************************************************/
void Timer_1ms_Base(void){
    if(BaseTimer.Timer_10ms <= 5000){
        BaseTimer.Timer_10ms += 1;
    }
    if(BaseTimer.Timer_2ms <= 5000){
        BaseTimer.Timer_2ms += 1;
    }
}

void Timer_2ms_Task(void){
    unsigned int n;
    unsigned char i;
    if(BaseTimer.Timer_2ms >= 2){
        n = BaseTimer.Timer_2ms / 2;
        BaseTimer.Timer_2ms = BaseTimer.Timer_2ms - (n * 2);

        TimerCtrlms(2 * n);
    }
}
void Timer_10ms_Task(void){
    unsigned int n;
    unsigned char i;
    if(BaseTimer.Timer_10ms >= 10){
        n = BaseTimer.Timer_10ms / 10;
        BaseTimer.Timer_10ms = BaseTimer.Timer_10ms - (n * 10);
        TimerCtrlms(10 * n);

        
    }
   
}