#include "base.h"
#include "asio.hpp"

#include "cClient.h"

#include <thread>

#include "asio/system_error.hpp"
#include "../LibProj/CsFunc/CsMessageBox.h"

//#include "lib_netsockets/Include/json_message.hh"

using namespace asio::ip;

cClient::cClient(uint16_t protocol) : enc(false), m_v(0), m_timets(0), m_a(false), m_sb(false), m_sproto(protocol), m_stopping(false), m_io_ctx(), m_sock(m_io_ctx)
{

}

bool cClient::Connect(const char* ip, uint16_t port)
{
	if (m_a)
	{
		asio::error_code ec;
		m_sock.cancel(ec);
		m_sock.close(ec);
	}

	m_sock.async_connect(tcp::endpoint(address().from_string(trim(ip)), port), [this](const std::error_code& ec)
	{
		if (m_stopping.load())
			return;

		if (ec)
		{
			OnDisconnected((char*)"10003");
			m_a = false;
			return;
		}

		OnConnected();
		if (!m_stopping.load())
			StartRead();
	});

	m_a = true;
	return true;
}

void cClient::EnableEncryption(unsigned int version)
{
	// TODO
}

void cClient::DoSend(cPacket& p)
{
	if (m_sb)
	{
#ifdef DEBUG_NETWORK
		//CsMessageBoxA(MB_OK, "Requests disabled for now");
#endif
		return;
	}

	asio::async_write(m_sock, asio::buffer(p.m_buf.data(), p.real_len), asio::transfer_exactly(p.real_len), [this, &p](const std::error_code& ec, size_t bt)
	{
		if (m_stopping.load())
			return;

		p.m_buf.consume(bt);

		if (ec)
		{
			OnDisconnected((char*)"10003");
			m_a = false;
			return;
		}
	});
}

void cClient::DoDisconnect()
{
	if (m_stopping.load())
		return;

	try
	{
		asio::error_code ec;
		if (m_sock.is_open())
		{
			m_sock.cancel(ec);
			m_sock.shutdown(tcp::socket::shutdown_both, ec);
			m_sock.close(ec);
		}
	}
	catch (...)
	{
	}

	m_a = false;
	OnDisconnected((char*)"10003");
}

void cClient::Stop()
{
	if (m_stopping.exchange(true))
		return;

	m_a = false;
	m_sb = true;

	try
	{
		asio::error_code ec;
		if (m_sock.is_open())
		{
			m_sock.cancel(ec);
			m_sock.shutdown(tcp::socket::shutdown_both, ec);
			m_sock.close(ec);
		}
	}
	catch (...)
	{
	}

	try
	{
		m_io_ctx.stop();
	}
	catch (...)
	{
	}

	if (m_t.joinable())
	{
		if (m_t.get_id() == std::this_thread::get_id())
			m_t.detach();
		else
			m_t.join();
	}

	m_read.m_buf.consume(m_read.m_buf.size());
	m_write.m_buf.consume(m_write.m_buf.size());
}

bool cClient::Bind()
{
	return true;
}

cClient::~cClient()
{
	Stop();
}

bool cClient::Run(int unk)
{
	if (m_t.joinable())
		return true;

	m_stopping.store(false);
	m_sb = false;
	m_io_ctx.restart();

	std::thread t([this]()
	{
		try
		{
			m_io_ctx.run();
		}
		catch (...)
		{
		}
	});

	m_t = std::move(t);
	return true;
}

void cClient::DoExecute()
{
}

void cClient::StartRead()
{
	asio::async_read(m_sock, m_read.m_buf.prepare(2), asio::transfer_exactly(2), [this](asio::error_code ec, std::size_t bt)
	{
		if (m_stopping.load())
			return;

		if (ec)
		{
			OnDisconnected((char*)"10003");
			m_a = false;
			return;
		}

		m_read.m_buf.commit(bt);

		uint16_t len;
		m_read.pop(len);

		m_read.real_len = len;

		int len2 = len - 2;
		if (len2 > 0)
			ReadAll(len2);
		else if (!m_stopping.load())
			StartRead();
	});
}

void cClient::ReadAll(int b)
{
	asio::async_read(m_sock, m_read.m_buf.prepare(b), asio::transfer_exactly(b), [this](asio::error_code ec, std::size_t bt)
	{
		if (m_stopping.load())
			return;

		if (ec)
		{
			OnDisconnected((char*)"10003");
			m_a = false;
			return;
		}

		m_read.m_buf.commit(bt);

		m_read.pop(m_sproto);

		OnExecute();

		m_read.m_buf.consume(m_read.m_buf.size());

		if (!m_stopping.load())
			StartRead();
	});
}

void cClient::push(void* data, size_t len, bool wlen)
{
	m_write.push(data, len, wlen);
}

void cClient::pop(void* data, size_t len, bool wlen)
{
	m_read.pop(data, len, wlen);
}

void cClient::mark(void* data, size_t len)
{
	m_write.mark(data, len); // TODO: what is this?
}

void cClient::endp(uint16_t id)
{
	m_write.endp(id);
}

void cClient::newp(uint16_t id)
{
	m_write.newp(id);
}
