#pragma once
#include "uart/ProtocolSender.h"
#include "service/popup_service.h"
#include "net/NetManager.h"
#include "service/BusinessConfig.h"
#include "manager/LanguageManager.h"
#include "base/http_client.h"
#include "base/strings.hpp"
#include "os/UpgradeMonitor.h"
#include "core/update_assistant.h"

namespace {
	base::UpdateAssistant assistant;
	base::VersionInfo info;

	enum Timer {
		kTimerProgress,
	};

	int loading_index = 0;
}

void NavibarSetProgressWindowVisible(bool visible) {
	mWindowProgressPtr->setVisible(visible);
}

void NavibarSetDialog1WindowVisible(bool visible) {
	mWindowDialog1Ptr->setVisible(visible);
}

void NavibarSetProgressMessage(const std::string& msg) {
	mTextViewProgressMessagePtr->setText(msg);
}

void NavibarSetDialog1Message(const std::string& msg) {
	mTextViewDialog1Ptr->setText(msg);
}

void NavibarProgressAnimation(bool visible) {
	mTextViewProgressLoadingPtr->setVisible(visible);
	if (visible) {
		loading_index = 0;
		mActivityPtr->registerUserTimer(kTimerProgress, 100);
		return;
	}
	mActivityPtr->unregisterUserTimer(kTimerProgress);
}

void NavibarDialog1ClickOk() {
	while (PopupService::instance()->busy_) {
		PopupService::instance()->busy_ = false;
	}
	//EASYUICONTEXT->hideNaviBar();
}

void updateDevice(){
	PopupService::Show([](PopupService* srv){

		base::HttpClient client;
		client.SetConnectionTimeout(5000);
		client.SetTimeout(120 * 1000);

		std::string url = getHttpGateway() + "/" + info.url.c_str();
		LOGD("请求更新文件的url： %s", url.c_str());

		base::HttpRequest req("GET", url, "");	// 去获取文件
		const char* tmp_file = "/tmp/update.img";
		base::HttpResponse response =
			client.Do(req, tmp_file, [srv, info](int64_t dltotal,
			int64_t dlnow, int64_t ultotal, int64_t ulnow){
	      LOGD("downloading %lld/%lld", dlnow, dltotal);

	      string msg = LANGUAGEMANAGER->getValue("Downloading") + " %.0f%%";
		  srv->SetMessage(base::format(msg.c_str(),
			  dltotal == 0 ? 0 : (dlnow * 1.0/dltotal * 100)));
		  return 0;
		});

		if (response.StatusCode() != 200) {	// 下载失败
			string msg = LANGUAGEMANAGER->getValue("DownloadFailed") + "%d";
		  srv->SetMessage(base::format(msg.c_str(), response.ErrorCode()));
		  return -1;
		}

		// TODO: 应该去判断一下，下载的版本是否真的大于当前版本号
		UpgradeMonitor::getInstance()->checkUpgradeFile("/mnt/extsd");
		LOGD("img版本-> %s", "");

		// 更新设备的版本
//		StoragePreferences::putString(WDKL_VERSION, info.version);
//		StoragePreferences::putInt(JHWS_VERSION_NUMBER, info.versionNo);

		system("touch /tmp/zkautoupgrade");
		UPGRADEMONITOR->checkUpgradeFile("/tmp");
		return 0;
	});
}

/**
 * 注册定时器
 * 填充数组用于注册定时器
 * 注意：id不能重复
 */
static S_ACTIVITY_TIMEER REGISTER_ACTIVITY_TIMER_TAB[] = {
	//{0,  6000}, //定时器id=0, 时间间隔6秒
	//{1,  1000},
};

/**
 * 当界面构造时触发
 */
static void onUI_init(){
    //Tips :添加 UI初始化的显示代码到这里,如:mText1Ptr->setText("123");
	std::string currentVersion = getVersion();
	int currentVersionNo = getVersionNo();

	mVersionPtr->setText(currentVersion);	// 写入界面的版本
	mVersionNoPtr->setText(to_string(currentVersionNo));	// 写入界面的版本号
	mWindowProgressPtr->setVisible(false);
	mWindowDialog1Ptr->setVisible(false);
}

/**
 * 当切换到该界面时触发
 */
static void onUI_intent(const Intent *intentPtr) {
	if (intentPtr != NULL) {
		std::string _appUpdate = intentPtr->getExtra(appUpdate);
		if (_appUpdate == "true") {
//			int ret = assistant.GetLatest("bed", &info);
//    		int currentVersionNo = StoragePreferences::getInt(JHWS_VERSION_NUMBER, GetVersionNo());
			int currentVersionNo = getVersionNo();
			LOGD("from server : %s %d, from device: %d", info.version.c_str(), info.versionNo, currentVersionNo);
			if (currentVersionNo < info.versionNo) {
				updateDevice();
			}
		}
	}
}

/*
 * 当界面显示时触发
 */
static void onUI_show() {

}

/*
 * 当界面隐藏时触发
 */
static void onUI_hide() {

}

/*
 * 当界面完全退出时触发
 */
static void onUI_quit() {

}

/**
 * 串口数据回调接口
 */
static void onProtocolDataUpdate(const SProtocolData &data) {

}

/**
 * 定时器触发函数
 * 不建议在此函数中写耗时操作，否则将影响UI刷新
 * 参数： id
 *         当前所触发定时器的id，与注册时的id相同
 * 返回值: true
 *             继续运行当前定时器
 *         false
 *             停止运行当前定时器
 */
static bool onUI_Timer(int id){
	switch (id) {
	case kTimerProgress: {
			loading_index = (loading_index + 1) % 8;
			mTextViewProgressLoadingPtr->setBackgroundPic(
					base::format("loading/%d.png", loading_index).c_str());
		}
		default:
			break;
	}
    return true;
}

/**
 * 有新的触摸事件时触发
 * 参数：ev
 *         新的触摸事件
 * 返回值：true
 *            表示该触摸事件在此被拦截，系统不再将此触摸事件传递到控件上
 *         false
 *            触摸事件将继续传递到控件上
 */
static bool onDeviceUpdateActivityTouchEvent(const MotionEvent &ev) {
    switch (ev.mActionStatus) {
		case MotionEvent::E_ACTION_DOWN://触摸按下
			//LOGD("时刻 = %ld 坐标  x = %d, y = %d", ev.mEventTime, ev.mX, ev.mY);
			break;
		case MotionEvent::E_ACTION_MOVE://触摸滑动
			break;
		case MotionEvent::E_ACTION_UP:  //触摸抬起
			break;
		default:
			break;
	}
	return false;
}
static bool onButtonClick_ButtonInstantly(ZKButton *pButton) {
    LOGD(" ButtonClick ButtonInstantly !!!\n");
    updateDevice();
    return false;
}

static bool onButtonClick_ButtonDialog1(ZKButton *pButton) {
    LOGD(" ButtonClick ButtonDialog1 !!!\n");
    return false;
}

static bool onButtonClick_ButtonUpdate(ZKButton *pButton) {
	LOGD(" ButtonClick ButtonUpdate !!!\n");
	mWindow1Ptr->hideWnd();

	PopupService::Show([](PopupService* srv){
		string msg = LANGUAGEMANAGER->getValue("Searching");
		srv->SetMessage(msg);
		if (!NETMANAGER->getEthernetManager()->isConnected()) {
			std::string msg = LANGUAGEMANAGER->getValue("EthernetDisconnect");
		  srv->SetMessage(msg);
		  return -1;
		}
		int ret = assistant.GetLatest("bed", &info);
		if (ret != 0) {
		  LOGE("get latest failed ret %d", ret);
		  msg = LANGUAGEMANAGER->getValue("GetVersionFailed") + "%d";
		  srv->SetMessage(base::format(msg.c_str(), ret));
		  return ret;
		}

//		int currentVersionNo = StoragePreferences::getInt(JHWS_VERSION_NUMBER, GetVersionNo());
		int currentVersionNo = getVersionNo();
//		LOGD("from server : %s %d, from device: %d", info.version.c_str(), info.versionNo, currentVersionNo);
		LOGD("更新版本，服务器版本-> %s， 版本号-> %d, 本机版本号-> %d", info.version.c_str(), info.versionNo, currentVersionNo);
		if (currentVersionNo >= info.versionNo) {	// 判断本身的版本大于新的版本时，不进行升级
			msg = LANGUAGEMANAGER->getValue("IsTheLastVersion");	// 已经是最新版本

		  srv->SetMessage(msg);
		  mWindow1Ptr->showWnd();
		  return -1;
		}

		mVersionNewPtr->setText(info.version);
		mVersionNoNewPtr->setText(to_string(info.versionNo));
		mWindowFindPtr->showWnd();
		return 0;
	});

	return false;
}
static bool onButtonClick_Button1(ZKButton *pButton) {
    LOGD(" ButtonClick Button1 !!!\n");
    EASYUICONTEXT->goBack();
    return false;
}
