#include "usr_config.h"
#include "app_Authen.h"
#include "system.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "bsp_time.h"
#include "ble_comm.h"
#include "bll_imu.h"
#include "app_flash.h"
#include "app_connect_manage.h"

/************************ º¯ÊýÉùÃ÷ ***********************************/
static BLE_Host_Tx_t m_Host_BLE_AUTHEN = {
	.n = 0,
	.t = 300,
};

static uint8_t Phoneflag =0;
static uint8_t HostAutodat =1;
static void cb_BLE_Client_BLE_AUTHEN(void* handle){
	DEBUG_LOG("Get cb_BLE_Client_BLE_AUTHEN\r\n");
	
	if(m_Host_BLE_AUTHEN.n <= 1){
		m_Host_BLE_AUTHEN.n =10;
		BLE_Host_Tx_Send(&m_Host_BLE_AUTHEN,BLE_AUTHEN,&HostAutodat,1);
	}
	else BLE_Host_Tx_Send(0,BLE_AUTHEN,&HostAutodat,1);
	Phoneflag =1;
}

static void cb_BLE_Host_BLE_AUTHEN(void* handle){
	BLE_Host_Rx_t* target = handle;
	BLE_Client_Tx_Send(0,BLE_AUTHEN,target->pDat,target->datLen); 
}

static void app_Authen_Process(void){
	static uint8_t state =0;
	static uint8_t host_state =1;
	static uint8_t Client_state =1;
	static uint32_t tim =0;
	
	if(mFlash.isHost){
		 if(!slave_isconnect()){
			 if(BLE_RIGHT_CONNTED == app_conneted_getRight() && 1 == host_state){
				  DEBUG_LOG("app_conneted_getRight>>>>>>>>\r\n");
					BLE_Host_Tx_Send(&m_Host_BLE_AUTHEN,BLE_AUTHEN,&HostAutodat,1);
			 }
			 host_state =0;
		 }
		 else {
			 host_state =1;
		 }
	}
	
	
	switch(state){
		case 0:
			    if(slave_isconnect()){
						if(0 == Client_state){
							state =1;
							tim = TIME_GetTicks();
							Client_state =1;
						}
					}
					else Client_state =0;
			    break;
	  case 1:
			    if(!slave_isconnect()){state =3;}
			    else if(1 == Phoneflag){state =2;}
			    else if(TIME_GetTicks() - tim >= 15000){
						 if(slave_isconnect())slave_disconnect();
						 else state =3;
						 DEBUG_LOG("AUTHEN over time\r\n");
					}
			    break;
		case 2:
			    if(!slave_isconnect()){state =3;}
			    break;
		case 3:
		default:state=0;Phoneflag =0;break;
	}
			   
}

void app_Authen_Init(void)
{
	Process_Start(1000,"app_Authon",app_Authen_Process);
	BLE_Client_Rx_Regist(BLE_AUTHEN,cb_BLE_Client_BLE_AUTHEN);
	DEBUG_LOG("BLE_Client_Rx_Regist %02x\r\n",BLE_AUTHEN);
  BLE_Host_Rx_Regist(BLE_AUTHEN,cb_BLE_Host_BLE_AUTHEN);
}


