#include "usr_config.h"
#include "bsp_time.h"
#include "selfcheck.h"
#include "system.h"
#include "nrf_gpio.h"
#include "app_charge.h"
#include "app_flash.h"
#include "ble_comm.h"
#include "bsp_adc.h"
#include "app_pair_chargerpin.h"
#include "app_chargerpin_conn_detect.h"
#include "hal_led.h"
#include "hal_charge.h"
#include "hal_mt.h"
#include "app_one_wire.h"
//==========================================================================
char open=0;
static uint8_t leddisplay_count = 0;
void pair_led_pcs(void)
{
    leddisplay_count++;
    if (leddisplay_count % 2 == 0)
    {
        LED_Start(LED_PAIR, COLOR_BLACK);
    }
    else
    {
        LED_Start(LED_PAIR, COLOR_WHITE);
    }
    if (leddisplay_count > 20)
    {
        leddisplay_count = 0;
        LED_Stop(LED_PAIR);
        Process_SetHoldOn(pair_led_pcs, 0);
        Process_Stop(pair_led_pcs);
    }
}
extern void close_white(void);
void start_pair_led(void)
{
	close_white();
	leddisplay_count = 0;
  Process_Start(500, "pair_led_pcs", pair_led_pcs);
  Process_SetHoldOn(pair_led_pcs, 1);
}
void stop_pair_led(void)
{
    if (leddisplay_count == 0)
    {
      return;
    }
    Process_Stop(pair_led_pcs);
    leddisplay_count = 0;
		LED_Stop(LED_PAIR);
}
void open_white(void)
{
	LED_Start(LED_PAIR, COLOR_LOWWHITE);
	
	PAIR_CHARGERPIN_PRINT("  ======================open_white open_white============================= \n");
	open=1;
}

void close_white(void)
{
	open=0;
	LED_Stop(LED_PAIR);
}
char white_isopen(void)
{
	return open;
}

void r_led_start(void)
{
	stop_pair_led();
	open_white();
}
PAIR_START_REGISTER(r_led_start);

void r_led_done(void)
{
	if(leddisplay_count!=0)open=0;
	else close_white();
}
PAIR_DONE_REGISTER(r_led_done);
//===========================================================================================

//写配对相关的flish
static int pair_writeflish(unsigned char *macAddr_L, unsigned char *macAddr_R)
{
    uint8_t offest = 0;
    if (mFlash.isHost)
    {
        offest = 3;
    }
    if (memcmp(macAddr_R, mFlash.mClient.macAddr + offest, 3) != 0)
    {
        goto writein;
    }
    if (mFlash.mClient.isConfig != 'C')
    {
        goto writein;
    }
    PAIR_CHARGERPIN_PRINT("mFlash.mClient.isConfig:%X\n", mFlash.mClient.isConfig);
    PAIR_CHARGERPIN_PRINT("mFlash.mClient.macAddr:%02X %02X %02X\n", mFlash.mClient.macAddr[0], mFlash.mClient.macAddr[1], mFlash.mClient.macAddr[2]);
    PAIR_CHARGERPIN_PRINT("mFlash.macHost:%02X %02X %02X\n", mFlash.macHost[0], mFlash.macHost[1], mFlash.macHost[2]);
    return 0;
writein:
    mFlash.mClient.isConfig = 'C';
    uint8_t i = 0;
    for (i = 0; i < 6; i++)
    {
        mFlash.macHost[i] = macAddr_L[i];
    }
    for (i = 0; i < 3; i++)
    {
        mFlash.mClient.macAddr[i + offest] = macAddr_R[i]; //从机自身mac地址
    }
    //保存数据到备份区域里面
    for (i = 0; i < RecordMacAddrL; i++)
    {
        mBackup.macAddr_L[i] = mFlash.macHost[i];         //主机地址
        mBackup.macAddr_R[i] = mFlash.mClient.macAddr[i]; //从机地址
    }
    mBackup.hardVersion = mFlash.mClient.hardVersion;
    mBackup.sotfVersion = mFlash.mClient.sotfVersion;
    mBackup.isConfig = mFlash.mClient.isConfig;
    if (Flash_SaveBackup() != ZONE_OP_SUCCESS)
    {
        Except_TxError(EXCEPT_Pair, "pair save backup fail");
    }
    DEBUG_LOG("mFlash.mClient.isConfig:%X\n", mFlash.mClient.isConfig);
    DEBUG_LOG("mFlash.mClient.macAddr:%02X %02X %02X\n", mFlash.mClient.macAddr[0], mFlash.mClient.macAddr[1], mFlash.mClient.macAddr[2]);
    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");
        return 0;
    }
    memset(&mFlash.mStep, 0, sizeof(FlashStep_t));
    if (Flash_SaveInfomation() != ZONE_OP_SUCCESS)
    {
        Except_TxError(EXCEPT_Pair, "Flash_SaveInfomation fail");
        return 0;
    }
    return 1;
}

static void load_adv_name_from_flish(void)
{
    char buf[16];
    memset(buf, 0, sizeof(buf));
    advertising_stop();
    sprintf(buf, "%02X%02X%02X%02X%02X%02X", mFlash.mClient.macAddr[0], mFlash.mClient.macAddr[1], mFlash.mClient.macAddr[2], mFlash.macHost[3], mFlash.macHost[4], mFlash.macHost[5]);
    DEBUG_LOG("advName(%d):%s\n", strlen(buf), buf);
    slave_set_adv_name(buf, strlen(buf));
    slave_adv_init();
}

static void load_scan_name_from_flish(void)
{
    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]);
    DEBUG_LOG("scanName1(%d):%s\n", strlen(buf), buf);
    host_set_scan_name(buf, strlen(buf));
}
static unsigned char reconnect_pcs_status = 0;
static void reconnect_pcs(void)
{
    switch (reconnect_pcs_status)
    {
    case 0:
        if (mFlash.isHost)
        {
            reconnect_pcs_status = 1;
            if (host_isconnect() == 1)
            {
                host_disconnect();
            }
        }
        else
        {
            reconnect_pcs_status = 2;
            if (slave_isconnect() == 1)
            {
                slave_disconnect();
            }
        }
        break;
    case 1:
        if (host_isconnect() == 0)
        {
            load_scan_name_from_flish();
            scan_start();
            reconnect_pcs_status = 4;
        }
        break;
    case 2:
        if (slave_isconnect() == 0)
        {
            load_adv_name_from_flish();
            advertising_start();
            reconnect_pcs_status = 4;
        }
        break;
    case 4:
        Process_SetHoldOn(reconnect_pcs, 0);
        Process_Stop(reconnect_pcs);
        reconnect_pcs_status = 5;
		
				start_pair_led();
        break;
    case 5:
        break;
    }
}
//===========================================================================================================
extern void app_pair_chargerpin_pcs(void);
void delsiflash(void)
{
	app_pair_chargerpin_pcs();
	Process_Stop(delsiflash);
}
__IO static char writefig=0;
unsigned char *savebuf;
void sucess_ev_cb(unsigned char *buf,int len)
{
	writefig=1;
	savebuf=buf;
	PAIR_CHARGERPIN_PRINT("  ======================PAIR SUCCESS============================= \n");
	Process_Start(10, "delsiflash", delsiflash);
}
void app_pair_chargerpin_pcs(void)
{
    int rev = 0;
    if (writefig == 1)
    {
        unsigned char Lbuff[6];
        unsigned char Rbuff[3];
        Get_MACaddr(Lbuff);
        Rbuff[0] = savebuf[0];
        Rbuff[1] = savebuf[1];
        Rbuff[2] = savebuf[2];
        rev = pair_writeflish(Lbuff, Rbuff);
        if (rev)
        {
            Process_Start(10, "reconnect_pcs", reconnect_pcs);
            Process_SetHoldOn(reconnect_pcs, 1);
            reconnect_pcs_status = 0;
        }
        else
        {
						start_pair_led();
        }
        writefig = 0;
    }
}
//======================================================================
void pair_start_pcs(void)
{
    extern void *pair_start$$Base;
    extern void *pair_start$$Limit;
    typedef void (*main_init_t)(void);
    for (int p = (unsigned int)&pair_start$$Base; p < (unsigned int)&pair_start$$Limit; p += 4)
    {
        (*(main_init_t *)p)();
    }
}

void pair_done_pcs(void)
{
    extern void *pair_done$$Base;
    extern void *pair_done$$Limit;
    typedef void (*main_init_t)(void);
    for (int p = (unsigned int)&pair_done$$Base; p < (unsigned int)&pair_done$$Limit; p += 4)
    {
        (*(main_init_t *)p)();
    }
}

//=================================================================================================
void send_start(void)
{
#define DELAY_PAIR_COUNT 100
	static unsigned int delay_pair_count=0;
	static char status=0;
	switch(status)
	{
		case 0:
			delay_pair_count=TIME_GetTicks();
			Process_Start(1, "send_start", send_start);
			Process_SetHoldOn(send_start, 1);
			status=2;
			break;
		case 2:
			if(nrf_gpio_pin_read(PIN_CHARGING)==0)
			{
				PAIR_CHARGERPIN_PRINT("  ==============================nrf_gpio_pin_read(PIN_CHARGING)==0 \n");
				status=3;
			}
			break;
    case 3:
        if (TIME_GetTicks() - delay_pair_count > DELAY_PAIR_COUNT)
        {
            delay_pair_count = TIME_GetTicks();
            nrf_gpio_pin_set(PIN_CHARGING);
            PAIR_CHARGERPIN_PRINT("  SEND PAIR TAG HIG; %d \n", TIME_GetTicks());
            status = 4;
        }
        break;
    case 4:
        if (TIME_GetTicks() - delay_pair_count > (DELAY_PAIR_COUNT + 100))
        {
            nrf_gpio_pin_clear(PIN_CHARGING);
            PAIR_CHARGERPIN_PRINT("  SEND PAIR TAG LOW; %d \n", TIME_GetTicks());
            status = 0;
						Process_Stop(send_start);
        }
        break;
	}
}

void into_event(void)
{
	chargerpin_one_ms_init(sucess_ev_cb);
	pair_start_pcs();
	if(mFlash.isHost==1)
	{
		send_start();
	}
}
void over_event(void)
{
	chargerpin_one_ms_uninit();
	pair_done_pcs();
}

void app_pair_chargerpin_Init(void)
{
	check_callback_regist(selfcheck_trigger_callback);
//	mFlash.isHost=0;
	if(mFlash.isHost!=HOST_SHOSE)
		app_pair_client_init(into_event,over_event);
	if(mFlash.isHost==HOST_SHOSE)
		app_pair_host_init(into_event,over_event);
}
