//
// Created by Luca on 9/15/2025.
//

#include "SHAL_CORE.h"

#include <cassert>

void SHAL_init(){
    systick_init(); //Just this for now

    SystemInit();

    PWR->CR3 |= PWR_CR3_LDOEN; //TODO don't hardcode

    SHAL_WAIT_FOR_CONDITION_US(((PWR->CSR1 & PWR_CSR1_ACTVOSRDY) != 0),500);
}


void systick_init(){
    SysTick->CTRL = 0;           //Disable first
    SysTick->LOAD = 0xFFFFFF;    //Max 24-bit
    SysTick->VAL  = 0;           //Clear
    SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk;
}

extern "C" void SysTick_Handler() {
    ticks++;
}

static uint32_t millis();



void SHAL_delay_us(uint32_t us){
    uint32_t ticks = us * (SystemCoreClock / 1000000U);
    uint32_t start = SysTick->VAL;

    //Calculate target value (may wrap around)
    uint32_t target = (start >= ticks) ? (start - ticks) : (start + 0x01000000 - ticks);
    target &= 0x00FFFFFF;

    //Wait until we reach the target
    if (start >= ticks) {
        //No wraparound case
        while (SysTick->VAL > target) {}
    } else {
        while (SysTick->VAL <= start) {} //Wait for wraparound
        while (SysTick->VAL > target) {} //Wait for target
    }
}

void SHAL_delay_ms(uint32_t ms){
    while(ms-- > 0){
        SHAL_delay_us(1000);
    }
}

bool SHAL_wait_for_bit_set_us(const volatile uint32_t* reg, const uint32_t mask, const uint16_t timeout) {
    if(SHAL_WAIT_FOR_CONDITION_US((*reg & mask) != 0, timeout)){
        return true;
    }
    return false;
}

bool SHAL_wait_for_bit_clear_us(const volatile uint32_t* reg, const uint32_t mask, const uint16_t timeout) {
    if(SHAL_WAIT_FOR_CONDITION_US((*reg & mask) == 0, timeout)){
        return true;
    }
    return false;
}

bool SHAL_wait_for_bit_set_ms(const volatile uint32_t* reg, const uint32_t mask, const uint16_t timeout) {
    if(SHAL_WAIT_FOR_CONDITION_MS((*reg & mask) != 0, timeout)){
        return true;
    }
    return false;
}

bool SHAL_wait_for_bit_clear_ms(const volatile uint32_t* reg, const uint32_t mask, const uint16_t timeout) {
    if(SHAL_WAIT_FOR_CONDITION_MS((*reg & mask) == 0, timeout)){
        return true;
    }
    return false;
}

bool SHAL_check_bit(const volatile uint32_t* reg, const uint32_t mask) {
    if ((*reg & mask) != 0) return true;
    return false;
}
