#include <zephyr.h>
#include <nrfx_rtc.h>
#include <nrfx_clock.h>
#include <hal/nrf_gpio.h>

#define LED_1 DT_GPIO_PIN(DT_ALIAS(led1), gpios)
#define LED_2 DT_GPIO_PIN(DT_ALIAS(led2), gpios)
#define BTN   DT_GPIO_PIN(DT_ALIAS(factoryrestore), gpios)

const nrfx_rtc_t rtc = NRFX_RTC_INSTANCE(0);
#define DESIRED_MSEC 1
uint8_t secs = 0;


static void rtc_handler(nrfx_rtc_int_type_t int_type)
{
  if(int_type == NRFX_RTC_INT_TICK)
  {
    nrf_gpio_pin_toggle(LED_1);
    
  }
  else if(int_type == NRFX_RTC_INT_COMPARE0)
  {
    nrf_gpio_pin_toggle(LED_2);
    int counter = nrfx_rtc_counter_get(&rtc);

    counter += (DESIRED_MSEC * 8);

    nrfx_rtc_cc_set(&rtc,0,counter,true);

    secs++;
    printk("secs: %d\n", secs);
  }
}


static void rtc_config(void)
{
  uint32_t err_code;

  nrfx_rtc_config_t rtc_config = NRFX_RTC_DEFAULT_CONFIG;
  rtc_config.prescaler = 4095; //tick = 32768 / (4095 + 1) = 8HZ = 125ms

  err_code = nrfx_rtc_init(&rtc, &rtc_config, rtc_handler);
  if (err_code != NRFX_SUCCESS) {
      printk("timer_init error: %d\n", err_code);
      return;
  }

  nrfx_rtc_tick_enable(&rtc, true);

    err_code = nrfx_rtc_cc_set(&rtc,0,(DESIRED_MSEC * 8),true);
    if (err_code != NRFX_SUCCESS) {
            printk("Failure in setup\n");
            return;
    }

  nrfx_rtc_enable(&rtc);


  IRQ_DIRECT_CONNECT(RTC0_IRQn, 0, nrfx_rtc_0_irq_handler, 0);
  irq_enable(RTC0_IRQn);

}

void main() {

    printk("RTC sample started\n");
  
    rtc_config();

    nrf_gpio_cfg_output(LED_1);
    nrf_gpio_cfg_output(LED_2);

    

}

