#include <errno.h>
#include <iostream>
#include <string>
#include <fcntl.h>
#include <arpa/inet.h>
#include "BaseSocket.h"

using namespace std;

class CServerSocket : public CBaseSocket
{
public:

	/// @brief 생성자.
	CServerSocket( const int & socket)
		: CBaseSocket(socket)	{	};

	/// @brief 소멸자.
	~CServerSocket() { Close(); };

	ssize_t ReadEx( void * vptr, size_t size )
	{ return Read(vptr, size); };

};

int main ( int argc, char * argv[] )
{
	if(argc != 4)
	{
		cerr << argv[0] << " server port file" << endl;
		return EXIT_FAILURE;
	}

	CServerSocket server(SOCKET_NOT_VALID);	
	if(server.Connect(argv[1], atoi(argv[2])))
	{
		cout << "connected : " << argv[1] << "," << argv[2]<< "," << argv[3] << endl;
	}
	else 
	{
		cout << "failed connection : " << errno << endl;
	}

	int f = open( argv[3], O_RDONLY );

	string sendval;
	if(f > 0 ) 
	{		
		while(true)
		{
			char szBuffer[1024] = {0};
			int n = 0;
			if((n = read(f, szBuffer,sizeof(szBuffer))) <=0)
				break;

			sendval.append(szBuffer,n);
		}

		close( f );
	}
	else
	{
		cerr << "The file '"<< argv[3] << "' was not opened" <<endl;
	}

	cout << "Send Data : " << sendval << ",Size : " << sendval.size () << endl;

	// send header 
	int sH = htonl(sendval.size());
	if(server.WriteN( &sH, 4 ) > 0)
	{
		cout << "Send success.[Header]"<< endl;
	}
	else
	{
		cerr << "Send fail.[Header]" << errno << endl;
	}

	// send body 
	if(server.WriteN( sendval.c_str(), sendval.size () ) > 0)
	{
		cout << "Send success.[Body]"<< endl;
	}
	else
	{
		cerr << "Send fail.[Body]" << errno << endl;
	}

	// read header
	int nR = 0;
	ssize_t r = server.ReadEx( &nR, 4);

	if(r < 0 )
	{
		cerr << "Socket Read Error.[Header]" << errno << endl;
	}
	else if ( r == 0)
	{
		cerr << "Server closed.[Header]" << errno << endl;
	}
	else 
	{
		nR = ntohl(nR);

		cout << "Resv success.[Header]," << nR << endl;
	}

	// read body
	string readval;
	while(nR > 0)
	{
		char szBuffer[1024] = {0};
		ssize_t r = server.ReadEx( szBuffer, sizeof(szBuffer) );
		
		if(r < 0 )
		{
			cerr << "Socket Read Error." << errno << endl;
			break;
		}
		else if ( r == 0)
		{
			cerr << "Server closed." << errno << endl;
			break;
		}
		else
		{
			readval.append(szBuffer, r);
		}
	}

	if(!readval.empty())
	{
		cout << "Read Data : " << readval << ", Size = " << readval.size() << endl;
	}

	cout << "end" << endl;

	// 그냥 시그널 대기
	pause();	
	
	server.Close();
	return EXIT_SUCCESS;
}
