#include "timer.h"

#include <DHCP/dhcp.h>
#include <DNS/dns.h>

#include "ch32v003fun.h"
#include "debug.h"

void tim2_init(void) {
  // Enable TIM2 clock
  RCC->APB1PCENR |= RCC_APB1Periph_TIM2;

  // Reset TIM2 to init all regs
  RCC->APB1PRSTR |= RCC_APB1Periph_TIM2;
  RCC->APB1PRSTR &= ~RCC_APB1Periph_TIM2;

  // Set prescaler to 14400-1, 10 kHz timer clock
  TIM2->PSC = 14400 - 1;

  // Set auto-reload value to 10,000-1 for 1 second overflow
  TIM2->ATRLR = 10000 - 1;

  // Enable update interrupt
  TIM2->DMAINTENR |= TIM_UIE;

  // Enable TIM2
  TIM2->CTLR1 |= TIM_CEN;

  NVIC_SetPriority(TIM2_IRQn, 0x40);
  NVIC_EnableIRQ(TIM2_IRQn);
}

void TIM2_IRQHandler(void) __attribute__((interrupt));
void TIM2_IRQHandler(void) {
  if (TIM2->INTFR & TIM_UIF) {
    TIM2->INTFR &= ~TIM_UIF;

    // DEBUG_PRINT("TIM2 IRQ\n");
    DHCP_time_handler();
    DNS_time_handler();
  }
}
