/*  $Id: socket_generic.h,v 1.15 2003/10/16 11:00:05 mbn Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
**
*/

#ifndef socket_generic
#define socket_generic

#include "socket_select.h"
#include "API/Core/System/keep_alive.h"
#include "API/Network/Socket/socket.h"
#include "event_trigger_socket.h"
#include <stack>

#ifndef WIN32
	#include <sys/socket.h>
	#include <netinet/in.h>
	#include <arpa/inet.h>
	#include <netdb.h>
	#include <sys/time.h>
	#include <unistd.h> 
#else
	#include <windows.h>
	typedef int socklen_t;
#endif

class CL_EventTrigger_Socket;
class CL_Socket_Generic;

class CL_Socket_KeepAliveHelper : public CL_KeepAlive
{
public:
	CL_Socket_KeepAliveHelper(CL_Socket_Generic *impl) : impl(impl) { return; }

	virtual void keep_alive();

	CL_Socket_Generic *impl;

	CL_Signal_v0 sig_read_triggered;

	CL_Signal_v0 sig_write_triggered;

	CL_Signal_v0 sig_exception_triggered;
	
	CL_Signal_v0 sig_disconnected;
};

class CL_Socket_Generic
{
//! Static operations:
public:
	static CL_IPAddress create_ip_address(const sockaddr_in &addr_in);

//! Construction:
public:
	CL_Socket_Generic();

	virtual ~CL_Socket_Generic();

//! Attributes:
public:
	int sock;

	int domain; // PF_INET, PF_INET6

	int protocol; // SOCK_STREAM, SOCK_DGRAM

	std::stack<std::string> push_stack;

	CL_EventTrigger_Socket *read, *write, *exception;

	CL_Socket_KeepAliveHelper *keep_alive_helper;

//! Operations:
public:
	void add_ref();

	void release_ref();

	static std::string get_error_message();

//! Overridables:
public:
	virtual CL_EventTrigger_Socket *create_read_trigger();

	virtual CL_EventTrigger_Socket *create_write_trigger();

	virtual CL_EventTrigger_Socket *create_exception_trigger();

//! Implementation:
private:
	int ref_count;
	
	//: True if the socket is connected, false if it is no longer in use
	bool valid;
	
	//: Internal function to shutdown a socket that has disconnected
	void disconnect();

	friend class CL_Socket_KeepAliveHelper;
};

#endif
