#include "app_ota.h"
#include "nrf_gpio.h"
#include "usr_config.h"
#include "bsp_time.h"
#include "system.h"
#include "hal_mt.h"
#include "app_host.h"
#include "app_charge.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "nrf_delay.h"
#include "app_flash.h"
#include "ble_comm.h"
#include "exception.h"

static ble_gap_addr_t mAddr;
static uint32_t isOTA=0;
static uint8_t isHostOTA=0;

static bool app_shutdown_handler(nrf_pwr_mgmt_evt_t event)
{
    switch (event){
        case NRF_PWR_MGMT_EVT_PREPARE_DFU:
            break;
        default:
            return true;
    }
    SEGGER_RTT_printf(0,"Into bootloader\n");
    return true;
}


NRF_PWR_MGMT_HANDLER_REGISTER(app_shutdown_handler, 0);

static void app_ota_Process(void)
{
	static uint8_t state = 0;
	char buf[16];

	uint8_t responhost =0;
	switch(state){
		case 0:{
			if(mFlash.isHost > 0){//左鞋
				 if(1 == isHostOTA){
					 SEGGER_RTT_printf(0,"------>isHostOTA\n");
					 state = 1;
					 host_disconnect();
					 nrf_ble_scan_stop();
					 Process_UpdatePeroid(app_ota_Process,60000);
					 BLE_Client_Tx_Send(0,BLE_DFU,&responhost,1);
				 }
			}
			else{
					if(isOTA==1){ isOTA = 0;
						if(slave_isconnect()) slave_disconnect();
						else advertising_stop();
						memset(buf,0,16);
						sprintf(buf,"SH_%02X%02X%02X%02X%02X%02X",mAddr.addr[5],mAddr.addr[4],mAddr.addr[3],mAddr.addr[2],mAddr.addr[1],mAddr.addr[0]);
						SEGGER_RTT_printf(0,"OTA name(%d):%s\n",strlen(buf),buf);
						slave_set_adv_name(buf,strlen(buf));
						slave_adv_init();
						state = 1;
						Process_UpdatePeroid(app_ota_Process,2000);
					}
			}
			break;}
		case 1:{
			if(mFlash.isHost > 0){//左鞋
				isHostOTA =0;
				state =0;
				SEGGER_RTT_printf(0,"------>left out to dfu\n");
			}
			else{
				if(slave_isconnect()==0){
					SEGGER_RTT_printf(0,"app_ota_Process advertising_start\r\n");
					advertising_start();
					Process_UpdatePeroid(app_ota_Process,60000);
					state = 2;
				}
				else slave_disconnect();
			}
			break;}
		case 2:{
			if(slave_isconnect()) state = 0;
			Process_UpdatePeroid(app_ota_Process,0);
			advertising_stop();
			memset(buf,0,16);
			
			#if BleNameHoldOn_ENANBLE 
			slave_set_adv_name((char *)RIGHT_NAME,sizeof(RIGHT_NAME));
			SEGGER_RTT_printf(0,"AdvName(%d):%s\n",sizeof(RIGHT_NAME),RIGHT_NAME);
		  #else
			sprintf(buf,"%02X%02X%02X%02X%02X%02X",mFlash.macHost[0],mFlash.macHost[1],mFlash.macHost[2],mFlash.mClient.macAddr[3],mFlash.mClient.macAddr[4],mFlash.mClient.macAddr[5]);
			SEGGER_RTT_printf(0,"ADV name(%d):%s\n",strlen(buf),buf);
			slave_set_adv_name(buf,strlen(buf));
			#endif
			
			Except_TxError(EXCEPT_DFU,"adv disconnted over time");
			slave_adv_init();
			advertising_start();
			state = 0;
			break;}
		  default:state = 0;Process_UpdatePeroid(app_ota_Process,0);break;
	}
	
	
}

static uint8_t number =0;
static uint8_t left_dfu_state =0;
static void app_ota_sendleftstate(void)
{
	 if(number>0){
		  BLE_Client_Tx_Send(0,BLE_DFU,&left_dfu_state,1);
		  number--;
	 }
	 else Process_Stop(app_ota_sendleftstate);
}

/*********************** 接收从机命令 ************************/
void cb_BLE_Host_R_DFU(void* handle)
{
	BLE_Host_Rx_t* target = handle;
	Process_Start(500,"app_ota_sendleftstate",app_ota_sendleftstate);
	number =10;
	left_dfu_state = target->pDat[0];
}

/*********************** 接收手机命令 ************************/
void cb_BLE_Client_R_DFU(void* handle)
{
	  SEGGER_RTT_printf(0,">>>>>>>>>>BLE_Client_R_DFU\n");
		BLE_Client_Rx_t* target = handle;
		if(mFlash.isHost>0){
			 if(*target->pDat == 0){isHostOTA = 1;
				  return; //左鞋不需要理会
			 }
			 else if(*target->pDat == 1){
				  BLE_Host_Tx_Send(0,BLE_DFU,target->pDat,1);	//发给从机
			 }
		}
		else {
			uint8_t responhost =1;
			BLE_Client_Tx_Send(0,BLE_DFU,&responhost,1);
			isOTA = 1;
		  SEGGER_RTT_printf(0,">>>>>>>>>>DFU start....\n");
		}
}

uint8_t app_ota_host_state(void)
{
	  return isHostOTA;
}

#if BleNameHoldOn_ENANBLE
extern uint8_t SaveFlashFlag_holdOn;
static void app_ota_SaveFlash(void){
	if(1 ==SaveFlashFlag_holdOn ){
		 SaveFlashFlag_holdOn =0;
		 if(Flash_SaveInfomation() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_DFU,"save information fail");
		 if(Flash_SaveBackup() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_DFU,"save backup fail");
		 uint8_t i =0;
		 SEGGER_RTT_printf(0,"mac host addr:");for(i=0;i<6;i++){SEGGER_RTT_printf(0,"%02X ",mFlash.macHost[i]);}SEGGER_RTT_printf(0,"\n");
		 SEGGER_RTT_printf(0,"mClient addr:");for(i=0;i<6;i++){SEGGER_RTT_printf(0,"%02X ",mFlash.mClient.macAddr[i]);}SEGGER_RTT_printf(0,"\n");
		 SEGGER_RTT_printf(0,"macAddr_L:");for(i=0;i<6;i++){SEGGER_RTT_printf(0,"%02X ",mBackup.macAddr_L[i]);}SEGGER_RTT_printf(0,"\n");
		 SEGGER_RTT_printf(0,"mBackup.macAddr_R:");for(i=0;i<6;i++){SEGGER_RTT_printf(0,"%02X ",mBackup.macAddr_R[i]);}SEGGER_RTT_printf(0,"\n");
	}
}
#endif


void app_ota_Init(void)
{
	uint32_t err_code = sd_ble_gap_addr_get(&mAddr); APP_ERROR_CHECK(err_code); 
	Process_Start(0,"app_ota_Process",app_ota_Process);
	BLE_Client_Rx_Regist(BLE_DFU,cb_BLE_Client_R_DFU);
  BLE_Host_Rx_Regist(BLE_DFU,cb_BLE_Host_R_DFU);
	
	#if BleNameHoldOn_ENANBLE
	SEGGER_RTT_printf(0,"mac addr:");for(int i=0;i<6;i++){SEGGER_RTT_printf(0,"%02X ",mAddr.addr[i]);}SEGGER_RTT_printf(0,"\n");
	uint8_t i=0;
	for(i=0;i<6;i++)if(mFlash.macHost[i] !=0xff)break;
	if(6 ==i){
		 for(uint8_t a=0;a<6;a++){
			   mFlash.macHost[a] = mAddr.addr[5-a];
			   mBackup.macAddr_L[a] = mAddr.addr[5-a];
		 }
		 SaveFlashFlag_holdOn =1;
	}
	
	Process_Start(1000,"app_ota_SaveFlash",app_ota_SaveFlash);
	#endif
	
	
}


