/*
 * update_assistant.cpp
 *
 *  Created on: 2022年5月5日
 *      Author: pengzc
 */

#include "update_assistant.h"
#include "base/http_client.h"
#include "base/json_object.h"
#include "utils/Log.h"
#include "restclient-cpp/restclient.h"
#include "storage/StoragePreferences.h"

#include "service/BusinessConfig.h"

namespace base {

UpdateAssistant::UpdateAssistant() {
  // TODO 自动生成的构造函数存根

}

int UpdateAssistant::GetLatest(const std::string& app_name, VersionInfo* info) {
	if (info == NULL) {
		return -1;
	}
//	using namespace base;
//	HttpClient client;
//	client.SetTimeout(6000);
//	client.SetConnectionTimeout(6000);
//	  client.SetCAInfoFilePath(CONFIGMANAGER->getResFilePath("cacert.pem"));

//	HttpRequest req("GET", getHttpGateway() + "/fly/" + app_name, "");
//	std::string url = getHttpGateway() + "/deviceBed/getAppVersion?device_type=304&part_id=" + StoragePreferences::getString(STORE_PARTID, "");
//	HttpRequest req("POST", url, "");
//	HttpResponse response = client.Do(req);
//
//	if (response.StatusCode() != 200) {
//		return response.ErrorCode();
//	}
//
//	base::JSONObject json;
//	if (!json.ParseObject(response.Body())) {
//		LOGD("Invalid response %s", response.Body().c_str());
//		return -1;
//	}
//	info->version = json.GetString("version_code", "");
//	info->versionNo = json.GetInt("version_no",1);
//	info->url = json.GetString("app_path", "");
//	info->file_size = json.GetInt("fileSize", 0);

	std::string url = getHttpGateway() + "/util/get_version?device_type=131&part_id=" + StoragePreferences::getString(STORE_PARTID, "");
	std::string content_type = std::string("application/json");

	LOGD("请求版本信息. url = %s", url.c_str());
	//发起HTTP POST请求
	RestClient::Response r = RestClient::post(url, content_type, "");
	if (r.code != 200) {
		LOGD("请求版本信息-> 错误代码： %d", r.code);
		return r.code;
	}

	LOGD("获得版本信息. result = %s", r.body.c_str());
	//解析json
	Json::Reader reader;
	Json::Value root;

	if(reader.parse(r.body, root, false)) {
		info->version = root["version_code"].asString();
		info->versionNo = root["version_no"].asInt();
		info->url = root["app_path"].asString();
		info->file_size = root["fileSize"].asInt();
		LOGD("versionNo: %d", info->versionNo);
	}
  return 0;
}

UpdateAssistant::~UpdateAssistant() {
  // TODO 自动生成的析构函数存根
}

} /* namespace base */
