#include "myhttp.h"

namespace ai_matrix
{
	MyHttp *MyHttp::ins = nullptr;
	MyHttp::GarbageCollector MyHttp::gc;
	std::mutex MyHttp::mx;

	MyHttp *MyHttp::getins()
	{
		//双层锁，确保线程安全
		if (ins == nullptr)
		{
			std::lock_guard<std::mutex> guard(mx); //防止异常发生不能解锁
			if (ins == nullptr)
			{
				ins = new MyHttp();
			}
		}
		return ins;
	}

	std::string MyHttp::socketHttp(std::string host, std::string request)
	{
		int sockfd; 
		struct sockaddr_in address;
		struct hostent *server;

		sockfd = socket(AF_INET, SOCK_STREAM, 0);
		address.sin_family = AF_INET;
		address.sin_port = htons(8100);
		server = gethostbyname(host.c_str());
		memcpy((char *)&address.sin_addr.s_addr, (char*)server->h_addr, server->h_length);

		if (-1 == connect(sockfd, (struct sockaddr *)&address, sizeof(address))) {
			
			return "";
		}

		write(sockfd, request.c_str(), request.size());

		char buf[1024 * 1024] = { 0 };


		int offset = 0;
		int rc;


		while (rc = read(sockfd, buf + offset, 1024))
		{
			offset += rc;
		}


		close(sockfd);

		buf[offset] = 0;

		return buf;

	}

	std::string MyHttp::postData(std::string host, std::string path, std::string post_content)
	{
		//POST请求方式
		std::stringstream stream;
		stream << "POST " << path;
		stream << " HTTP/1.0\r\n";
		stream << "Host: " << host << "\r\n";
		stream << "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3\r\n";
		stream << "Content-Type:application/x-www-form-urlencoded\r\n";
		stream << "Content-Length:" << post_content.length() << "\r\n";
		stream << "Connection:close\r\n\r\n";
		stream << post_content.c_str();
		return socketHttp(host, stream.str());
	}

	std::string MyHttp::getData(std::string host, std::string path, std::string get_content)
	{
		//GET请求方式
		std::stringstream stream;
		stream << "GET " << path << "?" << get_content;
		stream << " HTTP/1.0\r\n";
		stream << "Host: " << host << "\r\n";
		stream << "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3\r\n";
		stream << "Connection:close\r\n\r\n";
		return socketHttp(host, stream.str());
	}

}