#include "stdafx.h"
#include "utils.h"
#include "curl.h"
#include "json/reader.h"
#include "json/value.h"
#include <stdio.h>
#include <sys/stat.h>
#include <iostream>

void GetAppPath(WCHAR *path)
{
	int nPos = GetCurrentDirectory(MAX_PATH, path);
}

void LpbyteToCString(LPBYTE value, CString& result, int length)
{
	TCHAR buf[512];
	memset(buf, '\0', 512);
	memcpy(buf, value, length);
	result.Append(buf);
}

void ShowErrBox(DWORD err)
{
	LPVOID lpMsgBuf;
	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		err,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,
		0,
		NULL
		);

	MessageBox(NULL, (LPCTSTR)lpMsgBuf, _T("Error"), MB_OK);

	LocalFree( lpMsgBuf );
}

int gloabl_return = -1;
size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)  
{
	char *buf = (char*)malloc(size * nmemb + 1);
	memset(buf, '\0', size * nmemb + 1);
	memcpy(buf, ptr, size * nmemb);

	Json::Reader reader;
	Json::Value root;

	reader.parse(buf, root);
	gloabl_return = root["status"].asInt();

	std::cout<<buf<<std::endl;
	int written = fwrite(ptr, size, nmemb, (FILE *)stream);
	return written;
}

int Login()
{
	CURL *curl;
	CURLcode res;
	curl = curl_easy_init();    // ³υΚΌ»―

	curl_easy_setopt(curl, CURLOPT_URL,"http://healthroom.haoyong.me:80/users/login");
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "username=zktest&password=111111");
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);

	res = curl_easy_perform(curl);
	curl_easy_cleanup(curl);

	return gloabl_return;
}

char* UTF8ToEncode(const char* mbcsStr)
{
	wchar_t*  wideStr; 
	char*   unicodeStr; 
	int   charLen;

	charLen = MultiByteToWideChar(CP_UTF8, 0, mbcsStr, -1, NULL, 0);   
	wideStr = (wchar_t*) malloc(sizeof(wchar_t)*charLen); 
	MultiByteToWideChar(CP_UTF8, 0, mbcsStr, -1, wideStr, charLen); 

	charLen =WideCharToMultiByte(936, 0, wideStr, -1, NULL, 0, NULL, NULL);  
	unicodeStr = (char*)malloc(charLen);
	WideCharToMultiByte(936, 0, wideStr, -1, unicodeStr, charLen, NULL, NULL); 

	free(wideStr); 
	return unicodeStr;
}

std::vector<CString> mNames;
std::vector<CString> mId;

static void parse_search(const Json::Value& root)
{
	gloabl_return = root["status"].asInt();
	if (gloabl_return != 0)
	{
		gloabl_return = 1;
		return;
	}

	if (root["data"].isNull())
	{
		gloabl_return = 1;
		return;
	}

	Json::Value data = root["data"];
	if (data["count"].isNull() || data["list"].isNull())
	{
		gloabl_return = 1;
		return;
	}

	int count = data["count"].asInt();
	int list_size = data["list"].size();
	for (int i = 0; i < list_size; i++)
	{
		Json::Value val_image = data["list"][i];
		CString name(UTF8ToEncode(val_image["name"].asString().c_str()));
		mNames.push_back(name);
		mId.push_back(CString(val_image["identify"].asString().c_str()));
	}
}

size_t search_data(void *ptr, size_t size, size_t nmemb, void *stream)  
{
	char *buf = (char*)malloc(size * nmemb + 1);
	memset(buf, '\0', size * nmemb + 1);
	memcpy(buf, ptr, size * nmemb);

	Json::Reader reader;
	Json::Value root;

	reader.parse(buf, root);
	parse_search(root);

	int written = fwrite(ptr, size, nmemb, (FILE *)stream);
	free(buf);

	return written;
}

std::string WC2UT(const wchar_t* buf)
{
	int len = WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
	std::vector<char> utf8(len);
	WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);

	std::string temp(&utf8[0]);
	char buf_result[1024];
	memset(buf_result, '\0', 1024);
	int pos = 0;
	for (int i = 0; i < temp.length(); i++)
	{
		pos += _snprintf(buf_result + pos, 1024, "%%%02x", temp.at(i)&0xFF);
	}

	return std::string(buf_result);
}

std::string unicodeToUtf8(const wchar_t* buf)
{
	int len = WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
	std::vector<char> utf8(len);
	WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);
	return std::string(&utf8[0]);
}

int search(CString& name, CString& id_card)
{
	CURL *curl;
	CURLcode res;
	curl = curl_easy_init();

	std::string a = WC2UT(name.GetString());
	USES_CONVERSION;
	std::string url = std::string("http://healthroom.haoyong.me:80/api/old/oldList?name=")+WC2UT(name.GetString()) + "&identify=" + T2A(id_card);
	curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, search_data);

	res = curl_easy_perform(curl);
	curl_easy_cleanup(curl);

	return gloabl_return;
}

std::vector<CString>& getNames()
{
	return mNames;
}

std::vector<CString>& getIds()
{
	return mId;
}

bool util_upload(CString& name, CString id, CString path)
{
	CURL *curl;
	CURLcode code;
	CURLFORMcode formCode;
	long retcode = 0;
	long flen;
	char *slen;
	struct curl_httppost *post=NULL;
	struct curl_httppost *last=NULL;

	curl=curl_easy_init();

	USES_CONVERSION;
	curl_easy_setopt(curl,CURLOPT_URL, "http://healthroom.haoyong.me:80/api/health/healtRoomPicture");
	curl_formadd(&post, &last, 
		         CURLFORM_COPYNAME, "pictures",
				 CURLFORM_FILE, T2A(path),
				 CURLFORM_CONTENTTYPE, "image/jpeg", CURLFORM_END);

	std::string id_str = unicodeToUtf8(id.GetString());
	curl_formadd(&post,
		&last,
		CURLFORM_COPYNAME, "identify",
		CURLFORM_COPYCONTENTS, id_str.c_str(),
		CURLFORM_END);

	curl_formadd(&post,
		&last,
		CURLFORM_COPYNAME, "type",
		CURLFORM_COPYCONTENTS, "1",
		CURLFORM_END);

	curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);

	code=curl_easy_perform(curl);

	curl_formfree(post);
	curl_easy_cleanup(curl);
	return true;
}
