#include "app_connect_manage.h"
#include "bsp_time.h"
#include "system.h"
#include "ble_comm.h"
#include "app_flash.h"
#include "hal_charge.h"
#include "app_ota.h"
#include "app_game.h"
#include "exception.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "hal_led.h"
#include "exception.h"
#include "hal_mt.h"
#include "hal_battery.h"

/********************** 变量区 *************************/
#define Ble_update_connted_Error 60//一次最多更新蓝牙连接间隔 次数

/********************** 函数声明区 *************************/
extern uint8_t app_client_step_GetIsScan(void);

BLE_Host_Tx_t mBLE_Host_T_CONNET_R = {
	.n = 10,
	.t = 500,
	.cb = 0,
};

static uint16_t LedPlaytime =0;
static uint32_t LedBlinktim =0;

uint8_t app_conneted_getRight(void){
	uint8_t state =BLE_RIGHT_DISCONNTED;
	
	if('C' != mFlash.mClient.isConfig)
		 state =BLE_RIGHT_NOCONFIG;
	else if(host_isconnect())
		 state =BLE_RIGHT_CONNTED;
	
	#if BleNameHoldOn_ENANBLE 
	   if(host_isconnect())
		 state =BLE_RIGHT_CONNTED;
	#endif
	
	return state;
}

void app_connect_LED_Process(void)
{
	static uint8_t ResportCs_Flag = 0;
	static uint8_t state =0;
	static uint8_t host_state=0;
	switch(state){
		case 0:
			    if(slave_isconnect()){
						state =1;
						ResportCs_Flag = 0;
					}
			    break;
		case 1:
			    if(host_isconnect()){ 
							if(0 == ResportCs_Flag){ResportCs_Flag = 1;		
								host_state = app_conneted_getRight();
								BLE_Host_Tx_Send(&mBLE_Host_T_CONNET_R,BLE_CONNET_R,&host_state,1);
								DEBUG_LOG("====================>BLE_Host_T_CONNET_LED:%d\n",TIME_GetTicks());
							}
					}
					else if(ResportCs_Flag > 0)	{ResportCs_Flag = 0;
						  BLE_Host_Tx_Clear(&mBLE_Host_T_CONNET_R);
					}
					
					if(0 != LedPlaytime){
						 if(TIME_GetTicks() - LedBlinktim >=LedPlaytime){LedPlaytime =0;
							 LED_Stop(LED_OVERTURN);
							 Process_SetHoldOn(app_connect_LED_Process,0);
						 }
					}
					if(!slave_isconnect()){
						state =0;
						LedPlaytime =0;
						Process_SetHoldOn(app_connect_LED_Process,0);
						LED_Stop(LED_OVERTURN);
						BLE_Host_Tx_Clear(&mBLE_Host_T_CONNET_R);
					}
			    break;
		default:state =0;LedPlaytime =0;LED_Stop(LED_OVERTURN);break;
			    
	}
}

static void cb_BLE_BLINK_LED(void* handle)
{	
	BLE_Client_Rx_t* target = handle;
	uint8_t buf[2]={0};

	buf[0] = target->pDat[0];
	buf[1] = target->pDat[1];
	
  LedPlaytime = ((target->pDat[0]<<8) + target->pDat[1]);
	DEBUG_LOG("=======>cb_BLE_BLINK_LED,displaytime:%d\n",LedPlaytime);
	BLE_Host_Tx_Send(0,BLE_BLINK_LED,buf,2); 
	Process_SetHoldOn(app_connect_LED_Process,1);
	LedBlinktim = TIME_GetTicks();
	LED_Start(LED_OVERTURN,COLOR_GREEN);
}

void cb_Slave_Connect(void)
{
	DEBUG_LOG("=======>cb_Slave_Connect\n");
	if(mFlash.isHost) slave_update_conn_interval_request(30,30);
}

void cb_Host_Connect(void)
{
	DEBUG_LOG("=======>cb_Host_Connect\n");
}

void app_connect_Process(void)
{
	static uint8_t state = 0;
	static uint32_t cnt = 0;
	static uint16_t  update_temp = 0;
	static uint8_t ble_con_int = 0;//左右鞋蓝牙之间的连接间隔
	static uint8_t hostclientswitch =0;
	if(!mFlash.isHost){
		if(1 == hostclientswitch){hostclientswitch =0;
			 state = 0;
			 cnt = 0;
			 update_temp = 0;
			 ble_con_int = 0;
			 Process_SetHoldOn(app_connect_Process,0);
		}
		return;
	}
	
	if( 1 != hostclientswitch)hostclientswitch =1;
		
		
	switch(state){
			case 0:{
				if((app_client_step_GetIsScan()||slave_isconnect()||(hal_charge_Getstate()!=BLE_CHARGE_PULLOUT) ) && 0 == app_ota_host_state()){
					DEBUG_LOG("=======>scan_start:%d,%d\n",app_client_step_GetIsScan(),slave_isconnect());
					Process_SetHoldOn(app_connect_Process,1);
					scan_start();
					cnt = 0;
					state = 1;
				}
				if(mFlash.isHost && 0 == slave_isconnect()){
					if(host_isconnect())host_disconnect();
				} 
				break;}
			case 1:{
				if(app_client_step_GetIsScan()==0&&slave_isconnect()==0&&(hal_charge_Getstate()==BLE_CHARGE_PULLOUT)){
					Except_TxError(EXCEPT_DFU,"adv disconnted over time");
					DEBUG_LOG("=======>nrf_ble_scan_stop\n");
					nrf_ble_scan_stop();
					Process_SetHoldOn(app_connect_Process,0);
					state = 0;
				}else if(host_isconnect()){
					DEBUG_LOG("=======>host_isconnect\n");
					Process_SetHoldOn(app_connect_Process,0);
					if(mFlash.isHost){
						update_temp =0;
						ble_con_int = 0;
					}
					state =2;
				}
				if(++cnt>=100){ if(0 == app_client_step_GetIsScan() && 'C' == mFlash.mClient.isConfig)Except_TxError(EXCEPT_CONNET,"scan right shoes over time");
					DEBUG_LOG("=======>app_err_Set nrf_ble_scan_stop\n");
					nrf_ble_scan_stop();
					Process_SetHoldOn(app_connect_Process,0);
					state = 0;
				}
				break;}
			case 2:{
				if(app_game_GetGameMode()){//游戏模式下更新连接间隔
						if(ble_con_int !=2 && update_temp <= Ble_update_connted_Error){
							if(APP_SUCCESS ==  Ble_update_conn_interval(7.5,7.5)){
								ble_con_int =2;
								update_temp  =0;
							}
							else {
							  if(Ble_update_connted_Error == update_temp)Except_TxError(EXCEPT_CONNET,"update Ble conn interval 7.5ms fail");
								++update_temp;
							}
						}
				}else{
						if(ble_con_int !=1 && update_temp <= Ble_update_connted_Error){
							if(APP_SUCCESS ==  Ble_update_conn_interval(100,100)){
								ble_con_int =1;
								update_temp =0;
							}
							else {
							  if(Ble_update_connted_Error == update_temp)Except_TxError(EXCEPT_CONNET,"update Ble conn interval 100ms fail");
								update_temp++;
							}
						}
				}
				if(app_client_step_GetIsScan()==0 && slave_isconnect()==0 && (hal_charge_Getstate()==BLE_CHARGE_PULLOUT)){
					if(host_isconnect())host_disconnect();
				}
				if(!host_isconnect()){
					DEBUG_LOG("=======>host_disconnect\n");
					Process_SetHoldOn(app_connect_Process,0);
					state = 0;
				}
				
				break;}
			default:state=0;break;
		}
}

static void cb_Client_BLE_CONNET_R(void* handle)
{	
	uint8_t host_state=BLE_RIGHT_DISCONNTED;
	host_state =app_conneted_getRight();
  
	if(mFlash.isHost){
		if(BLE_RIGHT_CONNTED == host_state){
			 BLE_Host_Tx_Send(0,BLE_CONNET_R,&host_state,1);
		}
		else BLE_Client_Tx_Send(0,BLE_CONNET_R,&host_state,1);
	}
	else {
		host_state=BLE_RIGHT_CONNTED;
		BLE_Client_Tx_Send(0,BLE_CONNET_R,&host_state,1);
	}
	
}

static void cb_Host_BLE_CONNET_R(void* handle)
{	
	uint8_t host_state=BLE_RIGHT_CONNTED;
	BLE_Client_Tx_Send(0,BLE_CONNET_R,&host_state,1);
}

void app_connect_manage_Init(void)
{
	Process_Start(100,"connect",app_connect_Process);
	Ble_Slave_Connectd_Evt_Regist(cb_Slave_Connect);
	Ble_Host_Connectd_Evt_Regist(cb_Host_Connect);
	Process_Start(100,"connect_led",app_connect_LED_Process);
	BLE_Client_Rx_Regist(BLE_CONNET_R,cb_Client_BLE_CONNET_R);
	
	BLE_Host_Rx_Regist(BLE_CONNET_R,cb_Host_BLE_CONNET_R);
	
	BLE_Client_Rx_Regist(BLE_BLINK_LED,cb_BLE_BLINK_LED);
}


