/*
 * config.c
 *
 *  Created on: Jul 27, 2024
 *      Author: true
 */

#include "config.h"
#include "eeprom.h"



struct UserConf userconf;



static uint16_t checksum()
{
    uint16_t i;
    uint16_t sum = 0;

    uint8_t *uc = (uint8_t *)&userconf;

    // calculate checksum
    for (i = 0; i < sizeof(userconf) - 6; i++) {
        sum += *uc++;
    }

    return sum;
}

void userconf_load(uint8_t force_reset)
{
    uint16_t csum;

    eeprom_read_bytes(0, 0, (uint8_t *)&userconf, sizeof(userconf));
    csum = checksum();

    if ((userconf.checkval != CHECKVAL) || (userconf.checksum != csum) || force_reset) {
        // config is invalid; reset to default
        userconf.cursor_color      = CONF_CURSOR_WHITE;
        userconf.cursor_flash      = 4;                 // default flash rate
        userconf.ledprog_ena_mask  = 0;                 // no programs enabled

        userconf.ledprog_setting[0][0] = 2;             // rainbow: angle top left to bottom right
        userconf.ledprog_setting[0][1] = 25;            // rainbow: spacing

        userconf.ledprog_setting[1][0] = 8;             // lite then fade: fade rate
        userconf.ledprog_setting[1][1] = 192;           // lite then fade: hue

        userconf.ledprog_setting[2][0] = 127;           // twinkle: saturation
        userconf.ledprog_setting[2][1] = 6;             // twinkle: intensity

        userconf.ledprog_setting[3][0] = 5;             // alternate: offset in 22.5deg increments
        userconf.ledprog_setting[3][1] = 244;           // alternate: hue

        userconf.checksum = checksum();
        userconf.checkval = CHECKVAL;
    }
}

void userconf_save()
{
    userconf.checksum = checksum();
    userconf.checkval = CHECKVAL;

    // this eeprom writes in 16-byte pages only, so split up the data
    eeprom_write_bytes(0, 0x00, (uint8_t *)&userconf + 0x00, 16);
    eeprom_write_bytes(0, 0x10, (uint8_t *)&userconf + 0x10, 16);
}
