#include "app_utils.h"
#include <math.h>
#include "wm_crypto_hard.h"

static uint32_t millis_cnt = 0;

uint32_t millis(void)
{
    return millis_cnt;
}

void millis_run_cb(void *arg)
{
    millis_cnt++;
}

void us_delay(uint32_t us)
{
    struct tls_timer_cfg timer_config = 
	{
		.is_repeat = false,
		.unit = TLS_TIMER_UNIT_US,
		.timeout = 0xFFFFFFFF,
	};

	uint8_t timer_id = tls_timer_create(&timer_config);

    if(WM_TIMER_ID_INVALID == timer_id) return;

	tls_timer_start(timer_id);

    // Perform a blocking delay
    while(tls_timer_read(timer_id) < us);

    tls_timer_destroy(timer_id);
}

void ms_delay(uint32_t ms)
{
    struct tls_timer_cfg timer_config = 
	{
		.is_repeat = false,
		.unit = TLS_TIMER_UNIT_MS,
		.timeout = 0xFFFFFFFF,
	};

	uint8_t timer_id = tls_timer_create(&timer_config);

    if(WM_TIMER_ID_INVALID == timer_id) return;

	tls_timer_start(timer_id);

    // Perform a blocking delay
    while(tls_timer_read(timer_id) < ms);

    tls_timer_destroy(timer_id);
}

uint32_t random_gen_6_digit(void)
{
	unsigned char random_buf[6] = {0};
	uint32_t output_num = 0;

	tls_crypto_random_init(0x19031998, CRYPTO_RNG_SWITCH_16);
	tls_crypto_random_bytes(random_buf, sizeof random_buf);
	tls_crypto_random_stop();

	for(uint8_t i = 0; i < sizeof random_buf; i++)
	{
		// Ensures the last digit is not 0
		if(i == (sizeof random_buf) - 1 && random_buf[i] % 10 == 0)random_buf[i]++;
		output_num += (random_buf[i] % 10) * pow(10, i);
	}

	return output_num;
}