#include "stdafx.h"
#include "CNetWork.h"
#include <nlohmann/json.hpp>

#include <fmt/format.h>


CNetWork::CNetWork() : m_http_ret(http_f)
{

}

CNetWork::~CNetWork(void)
{

}

HTTPRET CNetWork::PostLogin(LPCSTR username, LPCSTR password, std::string& data)
{
	std::vector<cpr::Pair> p;
	p.push_back({ "email",username });
	p.push_back({ "password",password });
	std::string text = PostUrl("/api/client/v3/login", p);
	if (text.empty()) {

		return http_f;
	}

	data = text.c_str();

    return http_yes;
}

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

SStringA CNetWork::GetLastErrorA()
{
	return SStringA().Format("%s", m_error_msg.c_str()).GetBuffer(0);
}

SStringW CNetWork::GetLastErrorW()
{
	return S_CA2W(m_error_msg.c_str(),CP_UTF8).GetBuffer(0);
}

std::string CNetWork::GetUrl(std::string path, std::vector<cpr::Parameter> parame)
{
    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_http_status = r.error.code;
			m_error_msg = r.error.message;
		}

		return "";
	}



	return std::string("");
}

bool  write_data(std::string /*data*/, intptr_t /*userdata*/)
{

	return true;
}

bool CNetWork::Download(std::string path)
{

	std::string configdir = std::filesystem::current_path().string() + "\\" + CLASHCONFIGDIR;

	std::filesystem::path p(configdir);

	if (!std::filesystem::exists(p)) {
		std::filesystem::create_directory(p);
	}

	std::string configname = configdir + "\\" CLASHCONFIGNAME;

	std::ofstream ofs(configname);
	cpr::Url url{ path };
	cpr::Session session;
	session.SetUrl(url);
	cpr::Response response = session.Download(ofs);
	return response.status_code == 200;
}


void CNetWork::Init()
{

}

void CNetWork::UnInit()
{
}
