/*
 * Author: Jake Goodwin
 * Date: 2025
 * filename: ADC.c
 * description:
 */

/*DEVNOTES:
 * The CH32v003 micro-controllers have 8channels for the ADC that are
 * external and 2 internal channels.
 *
 * The channels/inputs are labeled as AIN0-AIN7
 */

/*CH32v003 ADC TO PINs:
 * A0 --> PA2
 * A1 --> PA1
 * A2 --> PC2
 * A3 --> PD2
 * A4 --> PD3
 * A5 --> PD5
 * A6 --> PD6
 * A7 --> PD4
 *
 * Because they don't exactly match up, I'll need to write up my own
 * way to do the mapping.
 */

#include "ADC.h"
#include "RegEdit.h"
#include "ch32v003hw.h"

#define MAX_PIN_NUM 7

static bool IsInvalidPin(uint8_t pin_num)
{
    if (pin_num > MAX_PIN_NUM)
    {
        return true;
    }
    return false;
}

void ADC_Setup(void)
{
}

void ADC_PowerOn(void)
{
    RegEdit_u32_SetBit((void *)&ADC1->CTLR2, ADC_ADON);
}

void ADC_PowerOff(void)
{
    RegEdit_u32_ClearBit((void *)&ADC1->CTLR2, ADC_ADON);
}

void ADC_Init(uint8_t pin_num)
{
    if (IsInvalidPin(pin_num))
    {
        return;
    }
}

void ADC_Enable(void)
{
    // Set the enable bit in the CTRLA register
    // RegEdit_SetBit((void *)&ADC0.CTRLA, 0);
}

void ADC_Disable(void)
{
    // Clear the enable ADC flag
    // RegEdit_ClearBit((void *)&ADC0.CTRLA, 0);
}

void ADC_SetPin(uint8_t pin_num)
{
    if (IsInvalidPin(pin_num))
    {
        return;
    }
    // RegEdit_ClearRegister((void *)&ADC0.MUXPOS);
    // RegEdit_SetNum((void *)&ADC0.MUXPOS, pin_num);
}

uint16_t ADC_ReadValue_Impl(uint8_t pin_num)
{
    // RegEdit_SetNum((void *)&ADC0.COMMAND, ADC_STCONV_bm);

    /* Wait until ADC conversion done */
    // while (!(ADC0.INTFLAGS & ADC_RESRDY_bm))
    //{
    //     ;
    // }

    /* Clear the interrupt flag by writing 1: */
    // ADC0.INTFLAGS    = ADC_RESRDY_bm;

    // uint16_t adc_val = (uint16_t)ADC0.RES;
    // adc_val          = adc_val >> 5;
    uint16_t adc_val = 0;
    return adc_val;
}

// Set the default for the function pointer.
uint16_t (*ADC_ReadValue)(uint8_t pin_num) = ADC_ReadValue_Impl;
