/*
 * userconf.c
 *
 *  Created on: Aug 3, 2023
 *      Author: true
 */


#include <stdint.h>
#include <string.h>

#include "hk32f030m.h"

#include "userconf.h"

#include "led_prog.h"
#include "led_sk6x_spi.h"



#define EEPROM_BASE_ADDR		0x0c000000;



UserConf_t uconf = {0};



void uconf_save()
{
	uint8_t i;
	UserConf_t usave;

	FLASH_Status status;

	uint8_t *eeprom = (uint8_t *)EEPROM_BASE_ADDR;
	uint8_t *u8save = (uint8_t *)&usave;

	memcpy((void *)&usave, (void *)&uconf, sizeof(uconf));

	// never save brightness as minimum value
	if (!usave.led_bright) usave.led_bright++;

	// while saving data, disable interrupts
	__disable_irq();

	// commit bytes to eeprom only if they differ
	FLASH_Unlock();
	for (i = 0; i < sizeof(uconf); i++) {
		if (*eeprom != *u8save) {
			// erase byte
			while (*eeprom) {
				status = EEPROM_EraseByte((uint32_t)eeprom);
				if (status != FLASH_COMPLETE) {
					while(1);
				}
			}

			// write new byte
			status = EEPROM_ProgramByte((uint32_t)eeprom, *u8save);
			if (status != FLASH_COMPLETE) {
				while(1);
			}
		}

		eeprom++;
		u8save++;
	}
	FLASH_Lock();

	// re-enable interrupts
	__enable_irq();
}

void uconf_restore(uint8_t force_defaults)
{
	uint8_t *eeprom = (uint8_t *)EEPROM_BASE_ADDR;

	if ((*eeprom != 0x1f) || force_defaults) {
		// nothing to restore. load defaults instead
		uconf.magic = UCONF_MAGIC;

		uconf.led_prog_idx = 3;		// rainbow
		uconf.led_bright = 4;		// 50% brightness
		uconf.led_zone = 7;			// all zones active

		ledprog_default();
	} else {
		// copy from eeprom to uconf
		memcpy((void *)&uconf, (void *)eeprom, sizeof(uconf));
	}

	// set settings from user config
	ledprog_change(uconf.led_prog_idx);
	led_sk6x_zone_ena(uconf.led_zone);
	led_sk6x_brightness(uconf.led_bright);
}
