#include <main.h>
#include <stdio.h>
#include <stm32g4xx_hal_conf.h>
#include <math.h>

#include "squeow.h"

/* SQUEOW

TIM3 eventi 98304000/(49152×200) 10hz
TIM2 PWM 98304000/2048 48khz

risoluzione PWM 4*2048 -> 8192 (13bit)

*/

uint8_t stato_audio;
uint16_t pwm_value, sample_value;
char display_buffer[16];
uint8_t rails_number;
uint16_t samples_ringbuf[SAMPLES_BUFFER_SIZE]; ///< buffer ad anello dei dati RX
uint16_t samples_ringbuf_input_index, samples_ringbuf_output_index;


void audio_play(uint16_t pbuf, uint8_t size){
/*
	char display_buffer[16];
        uint16_t static indice;
        indice++;
        snprintf(display_buffer, 10, "n %d", indice);
        ssd1306_SetCursor(0, 1);
        ssd1306_WriteString(display_buffer, Font_11x18, White);
//        ssd1306_UpdateScreen(&hi2c1);
*/
	for (uint8_t i=0; i<size; i++) {
		
	}

}

uint32_t sat_sub(uint16_t x, uint16_t y){
    uint16_t res = x - y;
    res &= -(res <= x);
    return res;
}

uint16_t u16_sine(void){
        static double angle;
        angle += SINE_INCREMENT;
         if(angle >= 6.28) angle = 0;
        return (uint16_t)((sin(angle)*0x7fff)+0x7fff);
}

uint16_t u12_sine(void){
        static double angle;
        angle += SINE_INCREMENT;
         if(angle >= 6.28) angle = 0;
        return (uint16_t)((sin(angle)*0x7ff)+0x7ff);
}

uint16_t sample(void){
/*
                        stato_audio == STATO_AUDIO_ADC;
                        HAL_ADC_Start(&hadc1);
                        if (HAL_ADC_PollForConversion(&hadc1, 10) == HAL_OK){
//                              store_sample(HAL_ADC_GetValue(&hadc1) << 4);
                                sample_value = HAL_ADC_GetValue(&hadc1);
                        }
                        HAL_ADC_Stop(&hadc1);
                        */
}

void store_samples(uint16_t *data, uint16_t size){
        for(uint16_t i = 0; i < size; ++i) {
              samples_ringbuf[samples_ringbuf_input_index] = data[i];
                store_sample(data[i]);
        }
}

void store_sample(uint16_t sample){
                samples_ringbuf[samples_ringbuf_input_index] = sample;
                ringbuf_increment(&samples_ringbuf_input_index, SAMPLES_BUFFER_SIZE_MASK);
}
