// TCPServer.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "hexdumpdata.h"
#include "mysocket.h"

int main(int argc, char* argv[])
{
	printf("Start\n");

	printf("Creating socket ...\n");
	int ListenSocket = MySocketOpen(SOCK_STREAM, 9101);

	if (ListenSocket != -1)
	{
		struct sockaddr_in SockAddr = {0};
		size_t SockAddrLength = sizeof(SockAddr);

		getsockname(ListenSocket, (struct sockaddr *)&SockAddr, &SockAddrLength);
		printf("Socket created on %s:%u\n", inet_ntoa(SockAddr.sin_addr), SockAddr.sin_port);

		printf("Listening ...\n");
		listen(ListenSocket, 1);

		while (1)
		{
			struct sockaddr_in AcceptSockAddr = {0};
			size_t AcceptSockAddrLength = sizeof(AcceptSockAddr);

			int ConnectedSocket = accept(ListenSocket, (struct sockaddr *)&AcceptSockAddr, &AcceptSockAddrLength);

			if (ConnectedSocket != -1)
			{
				printf("Accepting ...\n");
				printf("Connected to %s:%u\n", inet_ntoa(AcceptSockAddr.sin_addr), AcceptSockAddr.sin_port);

				unsigned char SendData[] =
				{
					0x1b, '$',
					'H', 'e', 'l', 'l', 'o', ' ',
					'W', 'o', 'r', 'l', 'd',
				};

				printf("Sending:\n");
				HexDumpData(SendData, sizeof(SendData));
				MySocketSend(ConnectedSocket, SendData, sizeof(SendData));

				unsigned char RecvData[256] = {0};
				int BytesReceived = 0;

				while ((BytesReceived = MySocketRecv(ConnectedSocket, RecvData, sizeof(RecvData))) > 0)
				{
					printf("Received:\n");
					HexDumpData(RecvData, BytesReceived);
				}

				printf("Closing connected socket\n");
				MySocketClose(ConnectedSocket);
			}
			else
			{
				printf("Accept failed\n");
				break;
			}
		}

		printf("Closing listen socket\n");
		MySocketClose(ListenSocket);
		printf("Finish\n");
	}
	else
	{
		printf("Socket creation failed\n");
	}

	return 0;
}
