/*********************************************************************
 * INCLUDES
 */
#include "app_pair.h"
#include "hal_ws2812.h"
#include "ble_comm.h"
#include "app_flash.h"
#include "hal_charge.h"
#include "hal_ble_common.h"
#include "bsp_time.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "hal_led.h"
#include "ble_advertising.h"

#define PAIR_DEBUGLOG_ENABLE 0

#if PAIR_DEBUGLOG_ENABLE
#define PAIR_DEBUG_LOG(format,...) SEGGER_RTT_printf(0,format, ##__VA_ARGS__);
#else 
#define PAIR_DEBUG_LOG(format,...) ;
#endif

static uint8_t ScanFinishFlag =0;
static char pair_name[8]={0};

void Pair_adv_cb(ble_gap_evt_adv_report_t const * p_adv_report)
{
	if(p_adv_report->rssi>-20 && p_adv_report->data.len==15 ){
//		PAIR_DEBUG_LOG("rssi %d: tx_power:%d\r\n",p_adv_report->rssi,p_adv_report->tx_power);
//		PAIR_DEBUG_LOG("addr:");for(int i=0;i<6;i++){PAIR_DEBUG_LOG("%02X,",p_adv_report->peer_addr.addr[5-i]);}PAIR_DEBUG_LOG("\r\n");
		
		if(ScanFinishFlag==0 && p_adv_report->data.p_data[8] == 'S' && p_adv_report->data.p_data[9] == 'H' && p_adv_report->data.p_data[10] == '_'){ 
			ScanFinishFlag =1;
			memset(pair_name,0,sizeof(pair_name));
			memcpy(pair_name,&p_adv_report->data.p_data[8],7);
		  PAIR_DEBUG_LOG("p_data:");for(int i=0;i<p_adv_report->data.len;i++){PAIR_DEBUG_LOG("%02X,",p_adv_report->data.p_data[i]);}PAIR_DEBUG_LOG("\r\n");
			PAIR_DEBUG_LOG("name:(%s)\r\n",pair_name);
		}
	}
}

static void app_pair_flash_save(void){
	
		mFlash.mClient.isConfig ='C';
		mBackup.hardVersion = mFlash.mClient.hardVersion;
		mBackup.sotfVersion = mFlash.mClient.sotfVersion;
		mBackup.isConfig = mFlash.mClient.isConfig;
	  
	  //保存数据到备份区域里面
		for (uint8_t i = 0; i < RecordMacAddrL; i++)
		{
				mBackup.macAddr_L[i] = mFlash.macHost[i];//从机地址
				mBackup.macAddr_R[i] = mFlash.mClient.macAddr[i];        //主机地址
		}
		
		if (Flash_SaveBackup() != ZONE_OP_SUCCESS){Except_TxError(EXCEPT_Pair, "pair save backup fail");}
		PAIR_DEBUG_LOG("mFlash.mClient.isConfig:%X\n", mFlash.mClient.isConfig);
		PAIR_DEBUG_LOG("mFlash.mClient.macAddr:%02X %02X %02X\n", mFlash.mClient.macAddr[0], mFlash.mClient.macAddr[1], mFlash.mClient.macAddr[2]);
		PAIR_DEBUG_LOG("mFlash.macHost:%02X %02X %02X \n", mFlash.macHost[0], mFlash.macHost[1], mFlash.macHost[2]);
		
		if (Flash_DeleteAllStep() != ZONE_OP_SUCCESS){Except_TxError(EXCEPT_Pair, "pair clear step fail");}
		memset(&mFlash.mStep, 0, sizeof(FlashStep_t));
		if (Flash_SaveInfomation() != ZONE_OP_SUCCESS){Except_TxError(EXCEPT_Pair, "Flash_SaveInfomation fail");}
}

static void app_ble_send_mac(){
	uint8_t buf[32];
	uint8_t L=0;
	uint8_t mymac[6];
	
	Get_MACaddr(mymac);
	
	memcpy(buf,mymac,6);
	L +=6;
	
	//硬件版本
	buf[L++] = (uint8_t)((uint32_t)HARDWARE_VERSION>>24);
	buf[L++] = (uint8_t)((uint32_t)HARDWARE_VERSION>>16);
	buf[L++] = (uint8_t)((uint32_t)HARDWARE_VERSION>>8);
	buf[L++] = (uint8_t)((uint32_t)HARDWARE_VERSION>>0);
	//软件版本
	buf[L++] = (uint8_t)(SOFTWARE_VERSION>>8);
	buf[L++] = (uint8_t)(SOFTWARE_VERSION>>0);
	
	if(BLE_CHARGE_INSERT == hal_charge_Getstate()||BLE_CHARGE_DONE == hal_charge_Getstate())	
	  buf[L++] = 1;
	else  
		buf[L++] = 0;
	
	if(mFlash.isHost)
		BLE_Client_Tx_Send(0,BLE_PAIR,buf,L);
	else 
		BLE_Host_Tx_Send(0,BLE_PAIR,buf,L);
}

static uint8_t UpdateScanFlag =0;
static uint8_t blink_cnt =0;

static void app_pair_Left_Process(void)
{
	if(!mFlash.isHost){return;}
	
	uint8_t charge_state_c = hal_charge_Getstate();
	if(UpdateScanFlag >0){
		if(host_isconnect()){host_disconnect();}
		else{
			app_pair_flash_save();
			char buf[16];
			memset(buf,0,sizeof(buf));
			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]);
		  PAIR_DEBUG_LOG("scanName(%d):%s\n",strlen(buf),buf);
		  
			if(APP_SUCCESS == host_set_scan_name(buf,strlen(buf))){
				 UpdateScanFlag =0;
			}
		}
	}
	if(blink_cnt > 0 && BLE_CHARGE_PULLOUT == charge_state_c ){
	  blink_cnt = 0;
		LED_Stop(LED_PAIR);
	}
}

uint8_t app_pair_UpdateScanNameFlag(void){
	return UpdateScanFlag;
}

static void app_pair_Right_Process(void)
{
	static uint8_t state =0;

	
	if(mFlash.isHost){
//		if(isScan)nrf_ble_scan_stop();
		return;
	}
	uint8_t charge_state_c = hal_charge_Getstate();

	switch(state){//ble_advertising_init_t init;
		case 0:
				 if((charge_state_c == BLE_CHARGE_INSERT || charge_state_c == BLE_CHARGE_DONE)){
						PAIR_DEBUG_LOG("<<<<<<<<<<<<<<<<<<<<<<<<\r\n");
						PAIR_DEBUG_LOG("start scan\r\n");
						advdata_report_Evt_Regist(Pair_adv_cb);
						ST_scan_stop();
						host_set_scan_name((char *)"***********",sizeof("***********"));
						ST_scan_start();
						state =1;
//					  connetflag = 0;
					  ScanFinishFlag = 0;
				 }
			   break;
		case 1: 
				 if(!(charge_state_c == BLE_CHARGE_INSERT || charge_state_c == BLE_CHARGE_DONE)){
					 PAIR_DEBUG_LOG("charge out\r\n");
//					 advdata_report_Evt_del(Pair_adv_cb);
					 ST_scan_stop();
					 state = 0;
					 LED_Stop(LED_PAIR);
					 if(host_isconnect())host_disconnect();
				 }
				 if(ScanFinishFlag>0){ScanFinishFlag = 0;
					 state =1;
					 advdata_report_Evt_del(Pair_adv_cb);
					 if(host_isconnect()){host_disconnect();}
					 host_set_scan_name(pair_name,strlen(pair_name));
					 ST_scan_start();
					 PAIR_DEBUG_LOG("ST_scan_start*********************\n");
//					 Process_UpdatePeroid(app_pair_Right_Process,100);
				 }
				 
				 if(host_isconnect()){
					 PAIR_DEBUG_LOG("1");
//					 if(connetflag==0){ connetflag = 1;
//						 ST_scan_stop();
//					 }
					 app_ble_send_mac();
					}
			   break;
				}
}

static void cb_Host_BLE_PAIR(void* handle)
{
	BLE_Host_Rx_t* target = handle;
	
	if(host_isconnect()){host_disconnect();}
	
	if(target->pDat[12]==0) return;
	  ST_scan_stop();
		blink_cnt = 1;
		LED_Start(LED_PAIR,COLOR_BLUE);
//		ST_scan_stop();
	 uint8_t ret =0,i =0;
	 uint8_t mymacbuf[6];
	
//	 PAIR_DEBUG_LOG(">>>>>>>>cb_Host_BLE_PAIR =%d \r\n",target->datLen);

    uint8_t GetMacAddr[6]={0};
	 memcpy(GetMacAddr,target->pDat,sizeof(GetMacAddr));
		
	 uint32_t hv = ((uint32_t)target->pDat[6]<<24)| ((uint32_t)target->pDat[7]<<16) | ((uint32_t)target->pDat[8]<<8) | ((uint32_t)target->pDat[9]<<0);
	 uint16_t sv = ((uint16_t)target->pDat[10]<<8) | ((uint16_t)target->pDat[11]<<0);
	
		
	 for(i=0;i<6;i++){
		if(mFlash.macHost[i] != GetMacAddr[i]){
			 ret =1;
			 break;
		 }
	 }

//	PAIR_DEBUG_LOG("target->pDat[12] %d\n",target->pDat[12]);
	 if(mFlash.mClient.hardVersion != hv || mFlash.mClient.sotfVersion != sv || ret !=0){
			PAIR_DEBUG_LOG("host config:%d %d %d %d\n",hv,sv,ret);
			PAIR_DEBUG_LOG("mFlash.mClient:%d %d %d %d\n\n",mFlash.mClient.hardVersion,mFlash.mClient.sotfVersion,mFlash.mClient.isConfig,ret);
			
			mFlash.mClient.hardVersion = hv;
			mFlash.mClient.sotfVersion = sv;
			Get_MACaddr(mymacbuf);
			
			for(i=0;i<6;i++){
				 mFlash.mClient.macAddr[i] = mymacbuf[i];	//从机自身mac地址
				 mFlash.macHost[i] = GetMacAddr[i];				//主机发过来的mac地址
			}
			
			app_pair_flash_save();
			
			char buf[16];
			memset(buf,0,sizeof(buf));
//					 
			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]);
			PAIR_DEBUG_LOG("advName(%d):%s\n",strlen(buf),buf);
			slave_set_adv_name(buf,strlen(buf));
			advertising_stop();
			slave_adv_init();
			PAIR_DEBUG_LOG(">>>>>>>>advertising_start =0 \r\n");
			advertising_start();
	}
}

static void cb_Client_BLE_PAIR(void* handle)
{
	 uint8_t ret =0;
	 uint8_t i =0;
	 uint8_t mymacbuf[6];
	 uint8_t RightMacAddr[6]={0};
	 BLE_Client_Rx_t* target = handle;
	
	 if(hal_charge_Getstate() == BLE_CHARGE_PULLOUT )return;

	 app_ble_send_mac();
	 
	
	 PAIR_DEBUG_LOG(">>>>>>>>cb_Client_BLE_PAIR =0;\r\n");
	
	 memcpy(RightMacAddr,target->pDat,sizeof(RightMacAddr)); 
	 uint32_t hv = ((uint32_t)target->pDat[6]<<24)| ((uint32_t)target->pDat[7]<<16) | ((uint32_t)target->pDat[8]<<8) | ((uint32_t)target->pDat[9]<<0);
	 uint16_t sv = ((uint16_t)target->pDat[10]<<8) | ((uint16_t)target->pDat[11]<<0);
	
	 blink_cnt = 1;
	 LED_Start(LED_PAIR,COLOR_BLUE);
	
	
	 for(i=0;i<6;i++){
			if(mFlash.mClient.macAddr[i] != RightMacAddr[i]){
				 ret =1;
				 break;
			}
	  }
	
	if(mFlash.mClient.hardVersion != hv || mFlash.mClient.sotfVersion != sv || ret !=0){
		  PAIR_DEBUG_LOG("mFlash config:%d %d %d %d\n\n",mFlash.mClient.hardVersion,mFlash.mClient.sotfVersion,mFlash.mClient.isConfig,ret);
		  mFlash.mClient.hardVersion = hv;
	    mFlash.mClient.sotfVersion = sv;
		  Get_MACaddr(mymacbuf);
		  for(i=0;i<6;i++){
				 mFlash.mClient.macAddr[i] = RightMacAddr[i]; 	//收到的从机mac地址
		     mFlash.macHost[i] = mymacbuf[i];	            //主机本身mac地址
	    }
			UpdateScanFlag =1;
			ST_scan_stop();
			if(host_isconnect()){host_disconnect();}
	}
	
	
}

void app_led_blink_process(){
	if(blink_cnt>0){
		if(blink_cnt%2) LED_SetColor(LED_PAIR,COLOR_BLUE);
		else LED_SetColor(LED_PAIR,COLOR_BLACK);
		if(blink_cnt>=20){
			blink_cnt = 0;
			LED_Stop(LED_PAIR);
		}
		blink_cnt++;
	}
}

void app_pair_Initialize(void)
{
	Process_Start(100,"app_pair_Right_Process",app_pair_Right_Process);
	
	Process_Start(100,"app_pair_Left",app_pair_Left_Process);
	
	Process_Start(500,"Blink_flag",app_led_blink_process);
	
	BLE_Client_Rx_Regist(BLE_PAIR,cb_Client_BLE_PAIR);
	BLE_Host_Rx_Regist(BLE_PAIR,cb_Host_BLE_PAIR);
	
}

 





