//#include "app/framework/plugin/network-steering/network-steering.h"
//#include "app/framework/plugin/network-steering/network-steering-internal.h"
#include "ikk-ota.h"
#include "ikk-debug.h"
#include "../driver/ikk-led.h"


#define LED_SLOW_BLINK_ON_TIME_MS		800
#define LED_SLOW_BLINK_OFF_TIME_MS		800
#define LED_FAST_BLINK_ON_TIME_MS		200
#define LED_FAST_BLINK_OFF_TIME_MS		200

#define LED_SLOW_BLINK_CONTINUE_TIME_MS	(60 * 1000)
#define LED_FAST_BLINK_CONTINUE_TIME_MS	(5 * 1000)



static OTAStatusEnum g_eOTAStatus = OTA_NORMAL;
static uint8_t g_u8OtaLedId = LED_UNKNOW_ID;
pOTACallback g_pOTACallback = NULL;

static void kOTAMoudleOptCallback(OTAStatusEnum status);


//__no_init OTAGpioStatusST g_stOTAGpioStatus @ 0x2000FFF0;

static OTAGpioStatusST g_stOTAGpioStatus;

OTAStatusEnum kGetOTAStatus(void)
{
	return g_eOTAStatus;
}


void kSetOTAStatus(OTAStatusEnum status)
{
	g_eOTAStatus = status;
}

void kOTAMoudleInit(pOTACallback callback, uint8_t led_id)
{
	g_pOTACallback = callback;
	g_u8OtaLedId = led_id;
}


void kOTAMoudleCallback(OTAStatusEnum status)
{
	//校验成功或失败保存gpio状态，待bootloader中恢复
	if (status == OTA_VERITY_SUCCEED || status == OTA_FAILED){
		iKonkeAfSelfPrint("OTA GPIO KEEP status(%d)\r\n", g_eOTAStatus);
	}

	if (g_pOTACallback){
		g_pOTACallback(status);
	}else {
		if (g_u8OtaLedId != LED_UNKNOW_ID){
			kOTAMoudleOptCallback(status);
		}
	}
}

static void kOTAMoudleOptCallback(OTAStatusEnum status)
{
	iKonkeAfSelfPrint("##############kOTAMoudleUserCallback status(%d)##################\r\n", status);
	static bool flg = false;//防止网关断电后,ota失败后会间隔快闪
	switch(status)
	{
		case OTA_NORMAL:
			break;
		case OTA_START:
			kLedOptTrigger(g_u8OtaLedId, 2 * LED_FAST_BLINK_ON_TIME_MS, 14 * LED_FAST_BLINK_ON_TIME_MS,\
					OTA_UPGRADE__CONTINUE_MAX_TIME_MS /(2 * LED_FAST_BLINK_ON_TIME_MS + 14 * LED_FAST_BLINK_ON_TIME_MS), LED_ON, LED_ON);
			g_eOTAStatus = OTA_START;
			flg = false;
			break;
		case OTA_DOWNLOAD_DONE:
		{

		  	g_eOTAStatus = OTA_DOWNLOAD_DONE;
		  	break;
		}
		case OTA_VERITY_SUCCEED:
			//校验成功，记录继电器状态
			//常亮5S
			kLedOptTrigger(g_u8OtaLedId, 25 * LED_FAST_BLINK_ON_TIME_MS,  LED_FAST_BLINK_ON_TIME_MS, 1, LED_ON, LED_ON);
			g_eOTAStatus = OTA_NORMAL;
			break;
		case OTA_FAILED:
			if (flg != true){
				kLedOptTrigger(g_u8OtaLedId, LED_FAST_BLINK_ON_TIME_MS, LED_FAST_BLINK_ON_TIME_MS,\
									LED_FAST_BLINK_CONTINUE_TIME_MS /(LED_FAST_BLINK_ON_TIME_MS + LED_FAST_BLINK_ON_TIME_MS), LED_ON, LED_ON);
				g_eOTAStatus = OTA_NORMAL;
			}
			flg = true;
			break;
		default:
			iKonkeAfSelfPrint("##############Err: OTA status is not exist\r\n");
			break;
	}
}
