#include "drv_clk.h"
#include "drv_misc.h"
#include "kit_debug.h"
#include "drv_rcc.h"

#define AIRCR_VECTKEY_MASK          ((uint32_t)0x05FA0000)
#define NVIC_PriorityGroup_0        ((uint32_t)0x700)
#define GPIO_REMAP_EN_SWO_DIS_JTAG  ((uint32_t)0x02000000)


NoArgCall systick_int_call;
KitResult drvSystemTick(uint8_t priority, uint16_t period, NoArgCall call)
{
    uint32_t  tick;
    KitResult res;

    KIT_ASSERT_PARAM((call != NULL) && (CLOCK_SYS_FREQ / 1000 * period) < SysTick_LOAD_RELOAD_Msk);
    tick = CLOCK_SYS_FREQ / 1000 * period; 
    if ((call != NULL) && (tick < SysTick_LOAD_RELOAD_Msk))
    {
        systick_int_call = call;
        SysTick->LOAD  = (tick & SysTick_LOAD_RELOAD_Msk) - 1;  /* set reload register */
        drv_misc_set_nvic(SysTick_IRQn, priority);                  /* set Priority for Cortex-M0 System Interrupts */
        SysTick->VAL   = 0;                                     /* Load the SysTick Counter Value */
        SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
                         SysTick_CTRL_TICKINT_Msk   |
                         SysTick_CTRL_ENABLE_Msk;               /* Enable SysTick IRQ and SysTick Timer */
        
        res = kKitResult_Ok;
    }
    else
    {
        res = kKitResult_ParamErr;
    }
                                                           
    return res;
}

void SysTick_Handler(void)
{
    KIT_ASSERT_PARAM(systick_int_call != NULL);
    
    systick_int_call();
}



