#include "stdafx.h"
#include "CServerList.h"






CServerList::CServerList() 
{
}

CServerList::~CServerList()
{
}

bool CServerList::Init(std::string data)
{
	
	try
	{
		vectlistmode.clear();

		nlohmann::json j = nlohmann::json::parse(data.begin(), data.end());

		if (j["ret"].get<int>() == 1)
		{
			
			auto data = j["data"];
			for (int i = 0; i < data.size(); i++) {
				
				CServerListMode m_serverlist_mode;
				m_serverlist_mode.type = data[i]["type"].get<std::string>();
				m_serverlist_mode.id = data[i]["id"].get<int>();
				m_serverlist_mode.name = data[i]["name"].get<std::string>();
				m_serverlist_mode.host = data[i]["host"].get<std::string>();
				m_serverlist_mode.group = data[i]["group"].get<std::string>();
				m_serverlist_mode.online_users = data[i]["online_users"].get<int>();

				if (m_serverlist_mode.type == "shadowsocks")
				{
					m_serverlist_mode.method = data[i]["method"].get<std::string>();
					m_serverlist_mode.passwd = data[i]["passwd"].get<std::string>();
				}
				else if (m_serverlist_mode.type == "v2ray")
				{
					m_serverlist_mode.method = data[i]["method"].get<std::string>();
					m_serverlist_mode.uuid = data[i]["uuid"].get<std::string>();
					m_serverlist_mode.v2_net = data[i]["v2_net"].get<std::string>();
					m_serverlist_mode.v2_type = data[i]["v2_type"].get<std::string>();
					m_serverlist_mode.v2_host = data[i]["v2_host"].get<std::string>();
					m_serverlist_mode.v2_path = data[i]["v2_path"].get<std::string>();
					m_serverlist_mode.v2_tls = data[i]["v2_tls"].get<std::string>();
					m_serverlist_mode.v2_sni = data[i]["v2_sni"].get<std::string>();
				}
				else if (m_serverlist_mode.type == "trojan") {
					m_serverlist_mode.passwd = data[i]["passwd"].get<std::string>();
					m_serverlist_mode.sni = data[i]["sni"].get<std::string>();
				}
				m_serverlist_mode.udp = data[i]["udp"].get<int>();
				m_serverlist_mode.port = data[i]["port"].get<int>();

				m_serverlist_mode.country_code = data[i]["country_code"].get<std::string>();

				vectlistmode.push_back(m_serverlist_mode);
			}

			 
			return true;

		}
		if (j["ret"].get<int>() == 445 || j["ret"].get<int>() == 446)
		{
		 
			this->m_error_msg = S_CA2W(j["msg"].get<std::string>().c_str(), CP_UTF8).GetBuffer(0);
			return false;
		}
		else
		{
			this->m_error_msg = S_CA2W(j["msg"].get<std::string>().c_str(), CP_UTF8).GetBuffer(0);
			return false;
		}


	}
	catch (...)
	{
		this->m_error_msg = L"解析数据错误,点击右上角刷新";
		return false;
	}
}

bool GreaterSort(CServerListMode a, CServerListMode b)
{
	return a.online_users < b.online_users;
}

void CServerList::MinimumSelectNode()
{

	if (vectlistmode.empty())
	{
		return;
	}
	auto t = vectlistmode;
	std::sort(t.begin(), t.end(), GreaterSort);

	if (!t.empty())
	{
		for each (CServerListMode itme in t)
		{
			if (itme.online_users > 0 && strcmp(itme.country_code.c_str(),"hk") == 0)
			{
				node_name = itme.name;
				break;
			} 
		}
	}
}
