#include <Arduino.h>
#include "settings.h"
#include "display.h"

Preferences preferences;

void loadSettings() {
  preferences.begin("settings", true); // true = readonly
  defaultBrightness = (uint8_t)preferences.getUInt("brightness", 50);
  gameInterval = (uint16_t)preferences.getUInt("interval", 100);
  colorMode = (uint8_t)preferences.getUInt("color_mode", 0); // 0 = static, 1 = simple RGB, 2 = dynamic aging (decay)
  colorDecay = (uint8_t)preferences.getUInt("color_decay", 5);
  colorR = (uint8_t)preferences.getUInt("color_r", 255);
  colorG = (uint8_t)preferences.getUInt("color_g", 255);
  colorB = (uint8_t)preferences.getUInt("color_b", 255);
  preferences.end();
  displayBrightness(defaultBrightness);
  setGameColor(colorR, colorG, colorB);
}

void saveSettings() {
  preferences.begin("settings", false);
  preferences.putUInt("brightness", defaultBrightness);
  preferences.putUInt("interval", gameInterval);
  preferences.putUInt("color_mode", colorMode);
  preferences.putUInt("color_decay", colorDecay);
  preferences.putUInt("color_r", colorR);
  preferences.putUInt("color_g", colorG);
  preferences.putUInt("color_b", colorB);
  preferences.end();
}

void clearSettings() {
  preferences.begin("settings", false);
  preferences.clear();
  preferences.end();
  preferences.begin("highscores", false);
  preferences.clear();
  preferences.end();
  ESP.restart();
}

bool updateHighscores(uint16_t games, uint16_t ticks, uint16_t cells) {
  bool changed = false;
  Highscores hs = getHighscores();
  preferences.begin("highscores", false);
  if (games > hs.games) {
    preferences.putUInt("games", games);
    changed = true;
  }
  if (ticks > hs.ticks) {
    preferences.putUInt("ticks", ticks);
    changed = true;
  }
  if (cells > hs.cells) {
    preferences.putUInt("cells", cells);
    changed = true;
  }
  preferences.end();  
  return changed;
}

Highscores getHighscores() {
  Highscores hs;
  preferences.begin("highscores", true);
  hs.games = preferences.getUInt("games", 0);
  hs.ticks = preferences.getUInt("ticks", 0);
  hs.cells = preferences.getUInt("cells", 0);
  preferences.end();  
  return hs;
}