/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "common/network/tcp_socket.hpp"

using namespace polygun::network;

#if defined(__unix__)
#include <sys/socket.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#elif defined(_WIN32)
#include <winsock2.h>
#endif

#if defined(__unix__)
#define INVALID_SOCK 1
#elif defined(_WIN32)
#define INVALID_SOCK static_cast<int>(INVALID_SOCKET)
extern unsigned g_initialized_sockets;
#endif

TCPSocket::TCPSocket() :
	m_fd(0)
{
	open_socket();

	// setup timeout for receiving
#if defined(__unix__)
	struct timeval tv;
	tv.tv_sec = 1;
	tv.tv_usec = 0;
#elif defined(_WIN32)
	const DWORD tv = 1000;
#endif
	setsockopt(m_fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
}

TCPSocket::~TCPSocket() {
	close();
}

void TCPSocket::connect(const std::string& ip, unsigned short port) {
	if(m_fd==0)
		open_socket();

	std::string resolved_ip = ip;
	struct hostent* he = gethostbyname(ip.c_str());
	if(he && he->h_addr_list[0]) {
		struct in_addr** addrs = reinterpret_cast<struct in_addr**>(he->h_addr_list);
		resolved_ip = inet_ntoa(*addrs[0]);
	}
		
	struct sockaddr_in addr = {0};
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(resolved_ip.c_str());
	addr.sin_port = htons(port);
	if(::connect(m_fd, (struct sockaddr*)&addr, sizeof(addr))<0)
		throw std::string("Failed to connect to "+ip+":"+std::to_string(port));
}

bool TCPSocket::send(const char* data, unsigned size) const {
#if defined(_WIN32) || defined(__serenityos__)
	const int flags = 0;
#elif defined(__unix__)
	const int flags = MSG_CONFIRM;
#endif
	return ::send(m_fd, data, size, flags)>0;
}

bool TCPSocket::recv(std::vector<uint8_t>& output) {
	uint8_t data[65536];
	ssize_t received = ::recv(m_fd, reinterpret_cast<char*>(data), sizeof(data), 0);
	if(received>0) {
		output.assign(data, data+received);
		return true;
	}
	return false;
}

void TCPSocket::close() {
#if defined(__unix__)
	::close(m_fd);
#elif defined(_WIN32)
	g_initialized_sockets--;
	if(g_initialized_sockets==0)
		WSACleanup();
	closesocket(m_fd);
#endif
	m_fd = 0;
}

void TCPSocket::open_socket() {
	m_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(m_fd==INVALID_SOCK)
		throw std::string("Failed to open TCPSocket");
}
