/* Reflow Oven Controller
*
* Copyright (C) 2020  Mario Hüttel <mario.huettel@gmx.net>
*
* This file is part of the Reflow Oven Controller Project.
*
* The reflow oven controller is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* The Reflow Oven Control Firmware is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the reflow oven controller project.
* If not, see <http://www.gnu.org/licenses/>.
*/

#include <reflow-controller/settings/settings.h>
#include <reflow-controller/settings/settings-sd-card.h>
#include <reflow-controller/settings/settings-eeprom.h>
#include <reflow-controller/hw-version-detect.h>

bool settings_use_eeprom;

int settings_save_calibration(float sens_deviation, float offset, bool active)
{
	if (settings_use_eeprom)
		return settings_eeprom_save_calibration(sens_deviation, offset, active);
	else
		return sd_card_settings_save_calibration(sens_deviation, offset, active);
}

int settings_load_calibration(float *sens_dev, float *offset)
{
	bool active;
	int res;

	if (settings_use_eeprom) {
		res =settings_eeprom_load_calibration(sens_dev, offset, &active);
		if (!res && !active)
			res = -1;
	} else  {
		res = -1;
	}

	if (res)
		res = sd_card_settings_try_load_calibration(sens_dev, offset);

	return res;
}

enum settings_load_result settings_load_pid_oven_parameters(struct oven_pid_settings *settings)
{
	return sd_card_settings_load_pid_oven_parameters(settings);
}

void settings_setup(void)
{
	if (get_pcb_hardware_version() >= HW_REV_V1_3)
		settings_use_eeprom = settings_eeprom_detect_and_prepare();
	else
		settings_use_eeprom = false;
}

enum settings_load_result settings_load_overtemp_limit(float *over_temp_limit)
{
	int res;
	float tmp;

	if (!over_temp_limit)
		return SETT_LOAD_ERR;

	if (!settings_use_eeprom)
		return SETT_LOAD_FILE_NOT_FOUND;

	res = settings_eeprom_load_overtemp_limit(&tmp);
	if (res)
		return SETT_LOAD_DISK_ERR;
	*over_temp_limit = tmp;

	return SETT_LOAD_SUCCESS;
}

int settings_save_overtemp_limit(float over_temp_limit, bool active)
{
	if (settings_use_eeprom)
		return settings_eeprom_save_overtemp_limit(over_temp_limit, active);
	else
		return -100;
}
