#ifndef POT_WATCH_H
#define POT_WATCH_H

#include "ch32fun.h"
#include <stdio.h>

#include "display.h"
#include "utils.h"

// Potentiometer Watch Functions
uint16_t last_f_pot = 0;
uint16_t last_amp_pot = 0;
#define POT_CHANGE_THRESH 40

#define POT_EN PD4

uint8_t pot_watch_check(uint16_t *f_pot, uint16_t *amp_pot) {
	// ADC is 10-bit, so 0-1023
	*f_pot &= 0x03FF;	// Mask to 10 bits
	*amp_pot &= 0x03FF; // Mask to 10 bits
	// printf("F_POT: %d, AMP_POT: %d\n", *f_pot, *amp_pot);
	// Check if pots have changed
	uint16_t f_pot_thresh_h = (last_f_pot < 1023 - POT_CHANGE_THRESH) ? last_f_pot + POT_CHANGE_THRESH : 1023;
	uint16_t f_pot_thresh_l = (last_f_pot > POT_CHANGE_THRESH) ? last_f_pot - POT_CHANGE_THRESH : 0;
	// TODO: apply averaging if needed?
	if (*f_pot > f_pot_thresh_h || *f_pot < f_pot_thresh_l) {
		last_f_pot = *f_pot;
		return 1; // Frequency pot changed
	}
	uint16_t amp_pot_thresh_h = (last_amp_pot < 1023 - POT_CHANGE_THRESH) ? last_amp_pot + POT_CHANGE_THRESH : 1023;
	uint16_t amp_pot_thresh_l = (last_amp_pot > POT_CHANGE_THRESH) ? last_amp_pot - POT_CHANGE_THRESH : 0;
	if (*amp_pot > amp_pot_thresh_h || *amp_pot < amp_pot_thresh_l) {
		last_amp_pot = *amp_pot;
		return 2; // Amplitude pot changed
	}
	// No change
	return 0; // No change
}

#endif
