/*
 * PSE_unit.c
 *
 *  Created on: Aug 9, 2023
 *      Author: leo
 */

#include "PSE_unit.h"

#include "fatfs.h"
#include "lvgl.h"

static void generate_default_units(pse_unit* units, pse_syringe* syringes, pse_stepper_conf* stepper_confs, uint8_t unit_num){
	for(int i = 0; i < unit_num; i++){
		units[i] = (pse_unit){
	      .enabled = i%2,
	      .port = i,
	      .flow = 1500*i,
	      .volume = 0,
	      .set_volume = 0,
	      .syringe = &syringes[i],
		  .stepper_conf = &stepper_confs[i],
	    };
	    syringes[i] = (pse_syringe){
	    	.name = "Test",
	    	.diameter = 26700,
	    };
	  }
}


// Load units from file
// Units configuration are saved as binary, in the order [pse_unit, pse_syringe, pse_stepper_conf] with each unit back to back
// In case of any error fallback to a default configuration
void load_units(pse_unit* units, pse_syringe* syringes, pse_stepper_conf* stepper_confs, uint8_t unit_num){
	// Open save file
	FIL saveFile;
	if(f_open(&saveFile, "PSE_save.txt", FA_READ) != FR_OK){
		lv_obj_t * mbox1 = lv_msgbox_create(NULL, "Error", "Could not load configuration to SD card", NULL, true);
		lv_obj_center(mbox1);
		generate_default_units(units, syringes, stepper_confs, unit_num);
		return;
	}

	// read configuration sequentially
	for(int i = 0; i < unit_num; i++){
		FRESULT res;
		UINT bytesRead;
		res = f_read(&saveFile, &units[i], sizeof(units[i]), &bytesRead);
		units[i].syringe = &syringes[i];
		units[i].stepper_conf = &stepper_confs[i];

		res += f_read(&saveFile, units[i].syringe, sizeof(pse_syringe), &bytesRead);
		res += f_read(&saveFile, units[i].stepper_conf, sizeof(pse_stepper_conf), &bytesRead);

		if(res != FR_OK){
			generate_default_units(units, syringes, stepper_confs, unit_num);
			return;
		}
	}

	f_close(&saveFile);
}

void save_units(pse_unit* units, uint8_t unit_num){
	// Open save file
	FIL saveFile;
	if(f_open(&saveFile, "PSE_save.txt", FA_WRITE | FA_OPEN_ALWAYS) != FR_OK){
		lv_obj_t * mbox1 = lv_msgbox_create(NULL, "Error", "Could not save configuration to SD card", NULL, true);
		lv_obj_center(mbox1);
		return;
	}

	for(int i = 0; i < unit_num; i++){
		FRESULT res;
		UINT bytesRead;
		res = f_write(&saveFile, &units[i], sizeof(units[i]), &bytesRead);
		res += f_write(&saveFile, units[i].syringe, sizeof(pse_syringe), &bytesRead);
		res += f_write(&saveFile, units[i].stepper_conf, sizeof(pse_stepper_conf), &bytesRead);

		if(res != FR_OK){
			return;
		}
	}

	f_close(&saveFile);
}
