#include "pch.h"
#include "CNetwork.h"
#include <nlohmann/json.hpp>
#include "CUtils.h"

CNetwork::CNetwork() : m_http_ret(http_no), m_http_status(0)
{
	Init();
}

CNetwork::~CNetwork(void)
{
	UnInit();
}

void CNetwork::SetUrl(LPCSTR url)
{
	m_url = url;
}


char* mystrcpy(char* dst, const char* src)
{
	assert(dst != NULL);
	assert(src != NULL);

	if (dst == src)
		return dst;

	int size = strlen(src) + 1;

	if (dst < src || src + size <= dst)
	{
		char* d = dst;
		const char* s = src;

		while (size--)
			*d++ = *s++;
	}
	else
	{
		char* d = dst + size - 1;
		const char* s = src + size - 1;

		while (size--)
			*d-- = *s--;
	}
	return dst;
}


HTTPRET CNetwork::PostLogin(LPCSTR username, LPCSTR password, LPCSTR& data)
{
	CUtils cutils;
	//请求
	std::vector<cpr::Pair> p;
	p.push_back({ "email",username });
	p.push_back({ "password",password });
	std::string text = PostUrl("/api/client/v2/login", p);
	if (text.empty()) {
		
		return http_f;
	}

	data = text.c_str();
	//USERINFO userinf;
	////memset(&userinf, NULL, sizeof(USERINFO));
	////解析
	//try
	//{
	//	nlohmann::json j = nlohmann::json::parse(data.begin(), data.end());

	//	if (j["ret"].get<int>() == 1)
	//	{
 //
	//		auto userinfo = j["data"]["user"];
	//		
	//		userinf.id = userinfo.at("id").get<int>();

	//		/*auto username = S_CA2W(userinfo.at("account").get<std::string>(), CP_UTF8);

	//		memset(userinf.username, NULL, sizeof(wchar_t));*/
	//		mystrcpy(userinf.username, userinfo.at("account").get<std::string>().c_str());
	//		mystrcpy(userinf.password, userinfo.at("passwd").get<std::string>().c_str());
	//		mystrcpy(userinf.expiretime, userinfo.at("expired_at").get<std::string>().c_str());
	//		mystrcpy(userinf.unusedTraffic, userinfo.at("unusedTraffic").get<std::string>().c_str());
	//		mystrcpy(userinf.uuid, userinfo.at("uuid").get<std::string>().c_str());
	//		mystrcpy(userinf.level, userinfo.at("level").get<std::string>().c_str());
	//		
	//		//strcpy(userinf.port, userinfo.at("port").get<std::string>().c_str());

	//		userinf.port = userinfo.at("port").get<int>();

	//		//lstrcpynW(username.c_str(), userinf.username, username.length());
	//		//std::copy(username.begin(), username.end(), userinf.username);
	//		 
	//		/*userinf.username = userinfo.at("account").get<std::string>();
	//		userinf.expiretime = userinfo.at("expired_at").get<std::string>();
	//		userinf.password = userinfo.at("passwd").get<std::string>();
	//		userinf.unusedTraffic = userinfo.at("unusedTraffic").get<std::string>();
	//		userinf.uuid = userinfo.at("uuid").get<std::string>();
	//		userinf.level = userinfo.at("level").get<std::string>();
	//		userinf.port = userinfo.at("port").get<int>();*/

	//	
	//		mystrcpy(userinf.access_token, j["data"]["access_token"].get<std::string>().c_str());

	//	


	//		return &userinf;

	//	}
	//	else
	//	{
	//		wchar_t* msg = NULL;


	//		m_error_msg = S_CA2A(j["msg"].get<std::string>(),CP_UTF8);
	//		return NULL;
	//	}


	//}
	//catch (...)
	//{
	//	m_error_msg = "解析登录数据错误,未知错误";
	//	return NULL;
	//}


	/*char* p = data.c_str();*/
	return http_yes;
}

 

//void CNetwork::GetServerlist()
//{
//	keymap.clear();
//	std::string path = "v1/nodeproess";
//	m_http_ret = http_start;
//	auto data = GetUrl(path, keymap);
//	if (data.empty())
//	{
//		m_http_ret = http_f;
//		m_error_msg = "";
//		m_error_msg.append("请求错误:网络问题,错误码:").append(std::to_string(m_http_status));
//		return;
//	}
//	//解析数据
//	/*if (!m_server_list)
//	{
//		m_error_msg = "server_list为空";
//		return;
//	}
//
//
//	if (!m_server_list->parse(data))
//	{
//		m_error_msg = m_server_list->GetLastErrorA();
//		m_http_ret = http_f;
//		return;
//	}*/
//
//
//	m_http_ret = http_end;
//}

 

 

void CNetwork::Init() {

 
}

void CNetwork::UnInit()
{
	/*if (m_server_list)
	{
		delete m_server_list;
		m_server_list = NULL;
	}

	if (m_userinfo)
	{
		delete m_userinfo;
		m_userinfo = NULL;
	}*/
}

 
 
HTTPRET CNetwork::GetHttpConnectstatus()
{
	return m_http_ret;
}

LPCSTR CNetwork::GetLastErrorA()
{
	return m_error_msg.c_str();
}

LPCWSTR CNetwork::GetLastErrorW()
{
	return S_CA2W(m_error_msg,CP_UTF8).c_str();
}

 

std::string CNetwork::GetUrl(std::string path, std::vector<cpr::Parameter> parame)
{
	 


	cpr::Parameters p;
	for (auto it = parame.begin(); it != parame.end(); ++it) {
		//auto s = fmt::format("{0}", it->first);
		/*p.AddParameter({ it->first, it->second }, {});*/
		p.Add(*it);
	}

	for (auto it = vectorBaseurl.begin(); it != vectorBaseurl.end(); ++it) {
		auto s = fmt::format("{0}/{1}", *it, path.c_str());
		
		cpr::Response r;

		if (parame.empty())
		{
			r = cpr::Get(cpr::Url{ s.c_str() });
		}
		else {
			r = cpr::Get(cpr::Url{ s.c_str() }, p,cpr::Header{ {"accept", "application/json"} });
		}
		
		if (r.status_code == 200 || r.status_code == 201)
		{
			return r.text;
		}
		else {
			m_http_status = r.status_code;
			return "";
		}

	}

	

	return std::string("");
}

std::string CNetwork::PostUrl(std::string path, std::vector<cpr::Pair> parame)
{ 

	auto s = fmt::format("{0}{1}", m_url, path.c_str());

	cpr::Response r;

	if (parame.empty())
	{
		r = cpr::Get(cpr::Url{ s.c_str() });
	}
	else {
		r = cpr::Post(cpr::Url{ s.c_str() }, cpr::Payload{ parame.begin(),parame.end() }, cpr::Header{ {"accept", "application/json"} });
	}

	if (r.status_code == 200 || r.status_code == 201)
	{
		return std::move(r.text);
	}
	else {
		m_http_status = r.status_code;
		if (m_http_status == 0)
		{
			m_error_msg = "获取数据失败，可能是您的网络问题更换备用尝试";
		}
		
		return "";
	}



	return std::string("");
}

