/*
 * preferences.c
 *
 *  Created on: Feb 22, 2022
 *      Author: radioman
 */

#include "preferences.h"
#include "stm32l1xx_hal.h"

static Pref_td Preferences[PREF_COUNT];

static const Pref_td SavedPreferences[PREF_COUNT] = PREF_DEFAULT_VALUES;

void PrefIncValue(PrefNames_t PrefName)
{
  Preferences[PrefName].value = (Preferences[PrefName].value +
      Preferences[PrefName].step) % (Preferences[PrefName].max_val + 1);
  Preferences[PrefName].unsaved = true;
}

void PrefSetValue(PrefNames_t PrefName, int val)
{
  Preferences[PrefName].value = val;
  Preferences[PrefName].unsaved = true;
}

int PrefGetValue(PrefNames_t PrefName)
{
  return Preferences[PrefName].value;
}

void PrefLoadFromFlash()
{
  for(int i = 0; i < PREF_COUNT; i++)
  {
    Preferences[i] = SavedPreferences[i];
  }
}

void PrefSaveToFlash()
{
  HAL_FLASH_Unlock();
  for(int i = 0; i < PREF_COUNT; i++)
  {
    if(Preferences[i].unsaved)
    {
      if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, (uint32_t)(&(SavedPreferences[i].value)), Preferences[i].value) == HAL_OK)
        Preferences[i].unsaved = false;
    }
  }
  HAL_FLASH_Lock();
}
