#include "app/nv_storage.h"
#include "bsp/bsp_driver.h"
#include "libs/crc16.h"
#include "libs/logger.h"
#include "foc/motor/motor_param.h"
#include "foc/foc_config.h"

#define mc_config_idx_0 (sn_page_index + 1)
#define mc_config_idx_1 (mc_config_idx_0 + 1)

#define sn_idx_back       (mc_config_idx_1 + 1)

#define mc_runtime_red_idx (sn_idx_back + 1)
#define mc_crit_err_idx (mc_runtime_red_idx + 1)

void nv_write_crit_errblock(u8 *data, int len) {
	fmc_write_data(mc_crit_err_idx, data, len);
}

void nv_read_crit_errblock(u8 *data, int len) {
	fmc_read_data(mc_crit_err_idx, data, len);
}

void nv_write_runtime_block(u8 *data, int len) {
	fmc_write_data(mc_runtime_red_idx, data, len);
}

void nv_read_runtime_block(u8 *data, int len) {
	fmc_read_data(mc_runtime_red_idx, data, len);
}

void nv_write_config_block(u8 idx, u8 *data, int len) {
	fmc_write_data(idx==0?mc_config_idx_0:mc_config_idx_1, data, len);
}

void nv_read_config_block(u8 idx, u8 *data, int len) {
	fmc_read_data(idx==0?mc_config_idx_0:mc_config_idx_1, data, len);
}


int nv_write_sn(u8 *data, int len) {
	mc_sn_t sn;
	memset(&sn, 0, sizeof(sn));
	len = min(32, len);
	memcpy(sn.sn, data, len);
	sn.len = len;
	sn.crc = crc16_get(data, len);
	fmc_write_data(sn_page_index, (u8 *)&sn, sizeof(sn));
	fmc_write_data(sn_idx_back, (u8 *)&sn, sizeof(sn));
	return len;
}
int nv_read_sn(u8 *data, int len) {
	mc_sn_t *sn;
	memset(&sn, 0, sizeof(sn));
	len = min(ARRAY_SIZE(sn->sn), len);
	
	sn = (mc_sn_t *)fmc_get_addr(sn_page_index);
	u16 crc16 = crc16_get(sn->sn, min(32, sn->len));
	if (crc16 == sn->crc) {
		memcpy(data, sn->sn, len);
		return len;
	}
	sn = (mc_sn_t *)fmc_get_addr(sn_idx_back);
	crc16 = crc16_get(sn->sn, min(32, sn->len));
	if (crc16 == sn->crc) {
		memcpy(data, sn->sn, len);
		return len;
	}
	return 0;
}

void nv_storage_init(void) {

}

