#include "main.h"
#include "settings.h"
#include "stm32g0xx_hal_flash.h"

SettingsStruct Settings;

void SettingsInit(void) {
	SettingsLoad();

	if (Settings.start[0] == 0xFFFF) { // Flash memory is clear
		SettinsDefault();
	}
}

void SettinsDefault(void) {
	// Default Value
	unsigned int ch;
	for(ch=0; ch<5; ch++) {
		Settings.start[ch] = 1000;
		Settings.fail[ch] = 0;
	}

	SettingsSave();
}

void SettingsSave(void) {
	uint32_t PageError = 0;
	FLASH_EraseInitTypeDef EraseInitStruct;

	HAL_FLASH_Unlock();

	EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
	EraseInitStruct.Page = 15; //FLASH_PAGE_NB - 1;
	EraseInitStruct.NbPages = 1;

	if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) == HAL_OK)
	{
		// Write setting
		uint64_t *source_addr = (void *)&Settings;
		uint64_t dest_addr = (uint64_t) FLASH_SETTINGS_START_ADDR;
		for (uint16_t i=0; i<SETTINGS_WORDS; i++) {
			HAL_FLASH_Program(FLASH_CR_PG, dest_addr, *source_addr);
			source_addr++;
			dest_addr = dest_addr + 8;
		}
	}

    HAL_FLASH_Lock();
}

void SettingsLoad(void) {
	uint32_t *source_addr = (uint32_t *)FLASH_SETTINGS_START_ADDR;
	uint32_t *dest_addr = (void *)&Settings;

	for (uint16_t i=0; i<SETTINGS_WORDS; i++) {
		*dest_addr = *(__IO uint32_t*)source_addr;
		source_addr++;
		dest_addr++;
	}
}

void SettingsReset(void) {
	uint32_t PageError = 0;
	FLASH_EraseInitTypeDef EraseInitStruct;

	HAL_FLASH_Unlock();

	EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
	EraseInitStruct.Page = 15; //FLASH_PAGE_NB - 1;
	EraseInitStruct.NbPages = 1;

	if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) == HAL_OK)
	{
		SettinsDefault();
	}

    HAL_FLASH_Lock();
}
