#include "app_flash.h"
#include "bsp_wdt.h"
#include "exception.h"
#include "system.h"
#include "hal_minifds.h"
#include "nrf_sdh_soc.h"
#include "app_step.h"
#include "nrf_pwr_mgmt.h"
#include "bsp_flash.h"

/*************************************
 *DEFINITION
 */
#define FLASH_HEAD									        0xAA5555AA

#define FLASH_BACKUP_START_ADDR       0x00073000UL
#define FLASH_BACKUP_END_ADDR_INFOR   0x00073FFFUL
#define FLASH_BACKUP_ADDR_PAGENUM 		  1

#define FLASH_INFOR_START_ADDR 0x00074000UL
#define FLASH_INFOR_END_ADDR   0x00076000UL
#define FLASH_INFOR_ADDR_PAGENUM 		2

#define FLASH_START_ADDR_STEP  0x00076000UL
#define FLASH_END_ADDR_STEP    0x00077FFFUL
#define FLASH_ADDR_STEP_PAGENUM 		2

#if FLASH_BACKUP_END_ADDR_INFOR>=FLASH_BACKUP_START_ADDR?0:1
#error BACKUP ADDER FAIL
#endif

#if FLASH_INFOR_END_ADDR>=FLASH_INFOR_START_ADDR?0:1
#error INFOR ADDER FAIL
#endif

#define MaxLength(a,b) 							a>b?a:b

typedef struct t_mflash_param_type{
  const char    *name;	   //参数名字
	void    *value;          //数据指针
	const uint8_t length;    //数据长度
}mflash_param_type;

const mflash_param_type All_Falsh_value[]={
{"inforhead",&mFlash.head,4},//不可调整
{"macHost",mFlash.macHost,RecordMacAddrL},
{"IsHost",&mFlash.isHost,1},

{"LR_FLAG",&mFlash.LR_FLAG,1},

{"startTime",mFlash.mStep.startTime,8},
{"stepCur",mFlash.mStep.stepCur,8},

{"step",mFlash.mStep.step,8},
{"step_num",&mFlash.mStep.step_num,4},
{"C_isConfig",&mFlash.mClient.isConfig,1},
{"C_hard",&mFlash.mClient.hardVersion,4},
{"C_sotf",&mFlash.mClient.sotfVersion,2},
{"C_macAddr",&mFlash.mClient.macAddr,RecordMacAddrL},
{"Errorflag",&mFlash.mFlashLog.Errorflag,1},
{"logData",mFlash.mFlashLog.logData,50},
{"PB_BR_V2E",&mFlash.mbattercb_t.preBestResult_Voltage2power,4},
{"PB_BR_C2P",&mFlash.mbattercb_t.preBestResult_chargeV2P_f,4},
{"PB_P_MAH",&mFlash.mbattercb_t.P_mAh,4},
{"PB_KG",   &mFlash.mbattercb_t.kg,4},
{"PP2",   &mFlash.mbattercb_t.P2,4},
{"PP1",   &mFlash.mbattercb_t.P1,4},
{"PCAP_MAH",&mFlash.mbattercb_t.Battery_capacity_mAh,4},
{"PTP4056",&mFlash.mbattercb_t.adc_tp4056_power,4},
{"PINIT", &mFlash.mbattercb_t.init,1},
{"PSTA",  &mFlash.mbattercb_t.sta,1},
{"PCV2P_INIT",&mFlash.mbattercb_t.chargeV2P_f_init,1},
{"PV2P_INIT",&mFlash.mbattercb_t.Voltage2power_init,1},

};

static const uint8_t MAX_mflash_param_LENGTH =sizeof(All_Falsh_value)/sizeof(All_Falsh_value[0]);

DEFINE_MINIINF(information, FLASH_INFOR_START_ADDR, FLASH_INFOR_END_ADDR, sdflash_write, sdflash_page_erase);

Flash_t 				mFlash={0};
FlashBackup_t 	mBackup={0};

/****************************************************接口****************************************************/
void Flash_Initialize(void)
{
	uint16_t i = 0;
	uint8_t length =0;

	uint32_t sucess = Flash_GetBackup(&mBackup);
	DEBUG_LOG("Flash_GetBackup (&mBackup):%d,MAX_mflash_param_LENGTH:%d\n",sucess,MAX_mflash_param_LENGTH);
	//查看是否有连续重启的标志位
  if(mBackup.head == FLASH_HEAD){
		if(mBackup.ErrStartCnt >= 5){
			
			Flash_DeleteAllInfor();
			Flash_DeleteAllStep();
			mBackup.ErrStartCnt =0;
			if(Flash_SaveBackup() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_FLASH,"save backup fail");
			
			DEBUG_LOG("mBackup.ErrorStartFlag >= 5!!!!!!!!!!!\n");
			NVIC_SystemReset();
		}
		else{
			mBackup.ErrStartCnt++;
			if(Flash_SaveBackup() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_FLASH,"save backup fail");
		}
	}
	
	minfds_init(&information);
	//读取记录
  for(i =0;i<MAX_mflash_param_LENGTH;i++){
		 if(MINIFDS_SUCCESS == pm_get_length(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),&length)){
				if(length == All_Falsh_value[i].length){
					 pm_find(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),(uint8_t *)All_Falsh_value[i].value,&length);
				}
		 }
  }
	
	DEBUG_LOG("Flash head read(%04X).\n",mFlash.head);
	//查看是否第一次写入
	if(mFlash.head !=FLASH_HEAD){  DEBUG_LOG("Flash first init(%04X),write infomation to flash.\n",mFlash.head);
		
		Flash_DeleteAllInfor();
		Flash_DeleteAllStep();
		
		memset((uint8_t*)(&mFlash),0,sizeof(Flash_t));
		mFlash.head = FLASH_HEAD;
		mFlash.isHost = _IS_HOST;
		//从备份预期中拷贝数据
		if(mBackup.head == FLASH_HEAD){
			 uint8_t i =0;
			 for(i=0;i<RecordMacAddrL;i++){
				 mFlash.macHost[i] =	mBackup.macAddr_L[i];	      //主机地址
				 mFlash.mClient.macAddr[i] = mBackup.macAddr_R[i];//从机地址
			 }
			 
			 DEBUG_LOG("Back macAddr_L:");for(i=0;i<RecordMacAddrL;i++){DEBUG_LOG("%02X:",mBackup.macAddr_L[i]);}DEBUG_LOG("\r\n");
			 DEBUG_LOG("Back macAddr_R:");for(i=0;i<RecordMacAddrL;i++){DEBUG_LOG("%02X:",mBackup.macAddr_R[i]);}DEBUG_LOG("\r\n");
			 
			 mFlash.mClient.hardVersion = mBackup.hardVersion;
			 mFlash.mClient.sotfVersion = mBackup.sotfVersion;
			 mFlash.mClient.isConfig = mBackup.isConfig;
			 mFlash.isHost = mBackup.isHost;
			 mFlash.LR_FLAG = mBackup.LR_FLAG;
			 DEBUG_LOG("Back Data:ifconfig:%d,hardVer:%d,backup.softversion:%d\n",mBackup.isConfig,mBackup.hardVersion,mBackup.sotfVersion);
		}else{
			 memset((uint8_t*)(&mBackup),0,sizeof(FlashBackup_t));
		   if(Flash_SaveBackup() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_FLASH,"save backup fail");
		}
		
		
		for(i =0;i<MAX_mflash_param_LENGTH;i++){
		   pm_add(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),(uint8_t *)All_Falsh_value[i].value,All_Falsh_value[i].length);
    }
		
		mFlash.head =0;
		//查看是否写入成功
		for(i =0;i<MAX_mflash_param_LENGTH;i++){
			if(MINIFDS_SUCCESS == pm_get_length(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),&length)){
				if(length == All_Falsh_value[i].length)
				{
					pm_find(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),(uint8_t *)All_Falsh_value[i].value,&length);
				}
			 }
		 }
	
		DEBUG_LOG("Flash head second read(%04X).\n",mFlash.head);
		if(mFlash.head != FLASH_HEAD){ 
			DEBUG_LOG("Flash write head fail.\n");
			Except_TxError(EXCEPT_FLASH,"Flash write head fail");
			return;
		}
		DEBUG_LOG("System reset...\n",mFlash.head);
		for(uint8_t i =0;i<6;i++){
			nrf_delay_ms(500);
			feed_watchdog();
		}
		NVIC_SystemReset();
	}
	else{
		 for(i =0;i<MAX_mflash_param_LENGTH;i++){
			 if(MINIFDS_SUCCESS == pm_get_length(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),&length)){
					if(length == All_Falsh_value[i].length){
						 pm_find(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),(uint8_t *)All_Falsh_value[i].value,&length);
					}
					else{
						 pm_delete(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name));
						 pm_add(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),(uint8_t *)All_Falsh_value[i].value,All_Falsh_value[i].length);
					}
			 }
			 else pm_add(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),(uint8_t *)All_Falsh_value[i].value,All_Falsh_value[i].length);
		}
  }
	DEBUG_LOG("err code :%s\n",mFlash.mFlashLog.logData);
	DEBUG_LOG("Flash init ok.\n");
	
	//TestHalFlashInterface();
}


/**
 @brief 设置清空脚步区域flash的标志
 @param 无
 @return 无
*/
static uint8_t FlashStep_ClearFlag =0;
void flash_SetClearStepFlag(void){
	FlashStep_ClearFlag =1;
}

uint32_t flash_GetStep_StartAddress(void){
	return FLASH_START_ADDR_STEP;
}

/**
 @brief 存储步数
 @param 无
 @return 错误代码
*/
uint32_t Flash_SaveStep(void)
{
	flash_OPER_Result err_code;
	uint32_t 				flash_data;
	
	#define Max_Hour PAGE_INT_SIZE * FLASH_ADDR_STEP_PAGENUM

	if(mFlash.mStep.step_num < Max_Hour)
	{
//		mFlash.mStep.stepCur[0] +=1 ;
		uint32_t step = app_step_GetStep_L() + app_step_GetStep_R(); //获取左右鞋步数
		
		flash_data =  ((step<<24 & 0xff000000) | (step<<8 & 0x00ff0000) | (step>>8 & 0x0000ff00) | (step>>24 & 0x000000ff));
		
	  //清空步数的flash step内容
	  if(1 == FlashStep_ClearFlag){
			if(Flash_DeleteAllStep() != ZONE_OP_SUCCESS){
				Except_TxError(EXCEPT_DATEStep,"clear step fail");
				return ZONE_ERROR_WRITE_FAIL;
			}
			mFlash.mStep.step_num  = 0;
			FlashStep_ClearFlag = 0;
	  }
		
		DEBUG_LOG("step %d,flash_data:%d,step_num:%d\n",step, flash_data,mFlash.mStep.step_num);
		err_code = sdflash_write((uint32_t*)(FLASH_START_ADDR_STEP + (mFlash.mStep.step_num * 4)), &flash_data, 1);
		if(err_code != FLASH_OP_SUCCESS)return ZONE_ERROR_WRITE_FAIL;
		
		mFlash.mStep.step_num++;
		mFlash.mStep.step[0] = mFlash.mStep.stepCur[0];
		mFlash.mStep.step[1] = mFlash.mStep.stepCur[1];	

		if(Flash_SaveInfomation() != ZONE_OP_SUCCESS){
			Except_TxError(EXCEPT_FLASH,"save information fail");
		}

		uint8_t i=4;
		uint8_t length =0;
		for(;i<5;i++){
		  if(MINIFDS_SUCCESS == pm_get_length(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),&length)){
				if(length == All_Falsh_value[i].length){
					 if(MINIFDS_SUCCESS == pm_find(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),(uint8_t *)All_Falsh_value[i].value,&length))
					 {
						 DEBUG_LOG(">>>>>>>>%s value:%d\n",All_Falsh_value[i].name,mFlash.mStep.stepCur[0]);
					 }
				}
		  }
    }
	}
	else return ZONE_ERROR_WRITE_FAIL;
	return ZONE_OP_SUCCESS;
}

/**
 @brief 删除所有步数
 @param 无
 @return 错误代码
*/
uint32_t Flash_DeleteAllStep(void)
{
	uint32_t errcode = ZONE_OP_SUCCESS;
	uint32_t pag_addr = 0;
	
	for(uint8_t i=0;i<FLASH_ADDR_STEP_PAGENUM;i++){
		pag_addr = (FLASH_START_ADDR_STEP +i*FLASH_PAGE_SIZE);
		errcode = sdflash_page_erase(pag_addr);
		if(errcode != NRF_SUCCESS)
		   return ZONE_ERROR_ERASE_FAIL;
	}
	return ZONE_OP_SUCCESS;
}

/**
 @brief 删除infromation的数据
 @param 无
 @return 错误代码
*/
uint32_t Flash_DeleteAllInfor(void)
{
	uint32_t errcode = ZONE_OP_SUCCESS;
	uint32_t pag_addr = 0;
	
	for(uint8_t i=0;i<FLASH_INFOR_ADDR_PAGENUM;i++){
		pag_addr = (FLASH_INFOR_START_ADDR +i*FLASH_PAGE_SIZE);
		errcode = sdflash_page_erase(pag_addr);
		if(errcode != NRF_SUCCESS)
		   return ZONE_ERROR_ERASE_FAIL;
	}
	return ZONE_OP_SUCCESS;
}

/**
 @brief 删除Backup的数据
 @param 无
 @return 错误代码
*/
uint32_t Flash_DeleteAllBackup(void)
{
	uint32_t errcode = ZONE_OP_SUCCESS;
	uint32_t pag_addr = 0;
	
	for(uint8_t i=0;i<FLASH_BACKUP_ADDR_PAGENUM;i++){
		pag_addr = (FLASH_BACKUP_START_ADDR +i*FLASH_PAGE_SIZE);
		errcode = sdflash_page_erase(pag_addr);
		if(errcode != NRF_SUCCESS)
		   return ZONE_ERROR_ERASE_FAIL;
	}
	return ZONE_OP_SUCCESS;
}


/**
 @brief 读取一个区域中指定位置的数据
 @param destination_addr[in] - 读取区域的地址
 @param pData[in] - 指向存储的buff
 @param dataLen[in] - 读取的长度，单位字节
 @return 错误代码
*/ 
uint32_t flash_Data_Read(uint32_t addr, uint32_t *pData, uint32_t dataLen){
	 if(pData != NULL && dataLen != 0){
		  if(addr < START_FSTORAGE_ADDR || addr >= END_FSTORAGE_ADDR){
				 return  ZONE_ERROR_ADDRESS_FAIL;
			}
			else  memcpy(pData, (uint32_t*)addr, dataLen);
	 }
	 return ZONE_OP_SUCCESS;
}

/**
 @brief 存储基本信息
 @param 无
 @return 错误代码
*/
uint32_t Flash_SaveInfomation(void)
{
	char result =0;
	for(uint8_t i =0;i<MAX_mflash_param_LENGTH;i++){
		 result = pm_update(&information,All_Falsh_value[i].name,strlen(All_Falsh_value[i].name),(uint8_t *)All_Falsh_value[i].value,All_Falsh_value[i].length);
		 if(result != MINIFDS_SUCCESS){
			 DEBUG_LOG("Flash_SaveInfomation fail name %s,result %d\r\n",All_Falsh_value[i].name,result);
			 return ZONE_ERROR_WRITE_FAIL;
		 }
	}
	return ZONE_OP_SUCCESS;
}

/**
 @brief 存储备份信息
 @param 无
 @return 错误代码
*/
uint32_t Flash_SaveBackup(void)
{
	uint32_t errcode = ZONE_OP_SUCCESS;
	uint32_t pag_addr = 0;
	mBackup.head = FLASH_HEAD;
	for(uint8_t i=0;i<FLASH_BACKUP_ADDR_PAGENUM;i++){
		pag_addr = (FLASH_BACKUP_START_ADDR +i*FLASH_PAGE_SIZE);
		errcode = sdflash_page_erase(pag_addr);
		if(errcode != NRF_SUCCESS)
		   return ZONE_ERROR_ERASE_FAIL;
	}
	errcode = sdflash_write((uint32_t*)FLASH_BACKUP_START_ADDR, (uint32_t*)&mBackup, sizeof(mBackup)/4);
	if(errcode != FLASH_OP_SUCCESS)return ZONE_ERROR_WRITE_FAIL;
	
	return ZONE_OP_SUCCESS;
	
}

/**
 @brief 获取备份信息
 @param 无
 @return 错误代码
*/
uint32_t Flash_GetBackup(FlashBackup_t *pbackup)
{
	return flash_Data_Read(FLASH_BACKUP_START_ADDR,(uint32_t*)pbackup, sizeof(FlashBackup_t));
}

/**
 @brief 保存日志信息
 @param[in] id    Fault identifier. See @ref NRF_FAULT_IDS.
 @param[in] pc    The program counter of the instruction that triggered the fault, or 0 if
                  unavailable.
 @param[in] info  Optional additional information regarding the fault. The value of the @p id
                  parameter dictates how to interpret this parameter. Refer to the documentation
                  for each fault identifier (@ref NRF_FAULT_IDS and @ref APP_ERROR_FAULT_IDS) for
                  details about interpreting @p info.
 @return 错误代码
*/
uint32_t Flash_SaveLog(uint32_t id, uint32_t pc, uint32_t info)
{
	memset((uint8_t*)(&mFlash.mFlashLog),0,sizeof(FlashLog));
	mFlash.mFlashLog.Errorflag =1;
	switch (id)
 {
	#if defined(SOFTDEVICE_PRESENT) && SOFTDEVICE_PRESENT
					case NRF_FAULT_ID_SD_ASSERT:
							memcpy(mFlash.mFlashLog.logData,"SD: ASSERTION FAILED\r\n",MaxLength(sizeof("SD: ASSERTION FAILED\r\n"),sizeof(mFlash.mFlashLog.logData)));
							break;
					case NRF_FAULT_ID_APP_MEMACC:
							memcpy(mFlash.mFlashLog.logData,"SD: INVALID MEMORY ACCESS\r\n",MaxLength(sizeof("SD: INVALID MEMORY ACCESS\r\n"),sizeof(mFlash.mFlashLog.logData)));
							break;
	#endif
					case NRF_FAULT_ID_SDK_ASSERT:
					{
							assert_info_t * p_info = (assert_info_t *)info;
							sprintf((char *)mFlash.mFlashLog.logData,"ASSERTION FAILED %s:%u\r\n",
														p_info->p_file_name,
														p_info->line_num);
							break;
					}
					case NRF_FAULT_ID_SDK_ERROR:
					{
							error_info_t * p_info = (error_info_t *)info;
						  
						  sprintf((char *)mFlash.mFlashLog.logData,"error:%u,%s:%u\r\n",
														p_info->err_code,
														p_info->p_file_name,
														p_info->line_num);
							DEBUG_LOG(">>>>>err code :%d,%s",p_info->err_code,mFlash.mFlashLog.logData);

							break;
					}
					default:
							sprintf((char *)mFlash.mFlashLog.logData,"UNKNOWN FAULT 0x%08X\n", pc);
							break;
	}
 
	return Flash_SaveInfomation();
}

/**
 @brief 测试halflash接口
 @param 无
 @return 无
*/
void TestHalFlashInterface(void)
{

//	uint2_t i; 
//	Flash_t m_testflash;
//	FlashBackup_t m_testbackup;
	
//	//测试基本信息和备份信息的写入和读取
//	for(i=0;i<10000;i++)
//	{
//		mFlash.mStep.step_num = i;
//		DEBUG_LOG("Flash_SaveInfomation[%d]:%d \n",i,Flash_SaveInfomation());
//		
//		DEBUG_LOG("Flash_SaveBackup[%d]:%d \n",i,Flash_SaveBackup());
//	}
//	
//	DEBUG_LOG("Flash_GetInfomation[%d]:%d \n",i,Flash_GetInfomation(&m_testflash));
//	DEBUG_LOG("m_testflash:%d \n",m_testflash.mStep.num);
//	
//	DEBUG_LOG("Flash_GetBackup[%d]:%d \n",i,Flash_GetBackup(&m_testbackup));
//	DEBUG_LOG("m_testbackup:%d \n",m_testbackup.hardVersion);
	
}


