#pragma once

#include <Arduino.h>
#include <EEPROM.h>

#include "config.h"

static const uint16_t TUNING_MAGIC = 0xDA7C;
static const int TUNING_EEPROM_ADDR = 0;

struct TuningData {
  uint16_t magic = 0;
  float heatKp = HEAT_PI_KP;
  float heatKi = HEAT_PI_KI;
};

inline uint8_t tuningChecksum(const TuningData &data) {
  const uint8_t *bytes = reinterpret_cast<const uint8_t *>(&data);
  uint8_t sum = 0;
  for (uint8_t i = 0; i < sizeof(TuningData) - 1; ++i) {
    sum ^= bytes[i];
  }
  return sum;
}

inline bool tuningLoad(TuningData &out) {
  EEPROM.get(TUNING_EEPROM_ADDR, out);
  const uint8_t stored = EEPROM.read(TUNING_EEPROM_ADDR + sizeof(TuningData));
  if (out.magic != TUNING_MAGIC) {
    return false;
  }
  return tuningChecksum(out) == stored;
}

inline void tuningSave(const TuningData &data) {
  EEPROM.put(TUNING_EEPROM_ADDR, data);
  EEPROM.write(TUNING_EEPROM_ADDR + sizeof(TuningData), tuningChecksum(data));
}

inline void tuningClear() {
  TuningData cleared;
  tuningSave(cleared);
}
