/*  Copyright (C) 2002 Tom Parker (tom@carrott.org),
                       Matthias Münch (matthias@amigaworld.de)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, Tom Parker and Matthias Münch give
    permission to link the code of this program with a TCP stack of your 
    choice, any official MUI libraries or classes and any custom MUI classes
    that should be necessary for the operation of this program.  This 
    exception also gives you permission to distribute linked combinations 
    including this software with any of the before-mentioned libraries and 
    classes.  You must obey the GNU General Public License in all respects for
    all of the code used other than that provided by the before-mentioned 
    libraries and classes.  As part of this exception you are obliged to 
    follow the license terms of the before-mentioned libraries, this license
    does not compel you to follow those terms, but if you do not then you may
    not link with those libraries.  If you modify this file, you may extend
    this exception to your version of the file, but you are not obligated to
    do so.  If you do not wish to do so, delete this exception statement from
    your version.
*/
/*
** connection code
*/

#include "common.h"
#include "network.h"

#ifdef NOMORPHOS
static struct EmulLibEntry net_on_packet;
#else
static void SAVEDS net_on_packet(void *udata, ikspak *pak);
#endif
static void net_handle_msg(ikspak *pak);
static void net_handle_iq(ikspak *pak);

struct netdata net;
struct Library *SocketBase = NULL;
static int SocketBaseRef = 0;
static long signum = -1;


int net_lala(void)
{
	if(SocketBase)
	{
		SocketBaseRef++;
		return 1;
	}

	if(signum == -1)
	{
		signum = AllocSignal(-1);
		if(signum == -1) return(0);
		net.sigmask = 1L << signum;
	}

	SocketBase = OpenLibrary("bsdsocket.library", 0);
	if(!SocketBase) return(0);
	SocketBaseTags(SBTM_SETVAL(SBTC_SIGIOMASK), net.sigmask, TAG_DONE);
	SocketBaseRef++;

	return 1;
}


void net_bibi(void)
{
	if(!SocketBase || SocketBaseRef == 0)
	{
		printf("DOH! report this to palpa\n");
		return;
	}

	SocketBaseRef--;
	if(SocketBaseRef == 0)
	{
		CloseLibrary(SocketBase);
		SocketBase = NULL;
		FreeSignal(signum);
		signum = -1;
		net.sigmask = 0;
	}
}


void net_connect(void)
{
	char *tmp;

	if(net.state != NET_OFF) return;

	if(!net_lala())
	{
		gui_state("Where is the TCP/IP stack?");
		return;
	}

	tmp = strdup(prf.user);
	net.id = iks_id_new(NULL, tmp);
	free(tmp);
	if(!net.id || !net.id->server || !net.id->user)
	{
		gui_state("Check your Jabber ID");
		net_bibi();
		return;
	}
	if(!net.id->resource)
		/* FIX ME */ net.id->resource = "Jabberwocky";

	net.parser = iks_jabber_new(&net, &net_on_packet);
	if(!net.parser) return;
	iks_set_logging(net.parser, &console_logger);

	net.state = NET_CONNECT;
	gui_state("Connecting...");
	if(!iks_connect_tcp(net.parser, net.id->server, 0))
	{
		net_disconnect("Cannot connect!");
		return;
	}
}


void net_disconnect(char *msg)
{
	net.state = NET_OFF;
	net.sigmask = 0;

	if(net.parser)
	{
		iks_parser_delete(net.parser);
		net.parser = NULL;
	}

	roster_reset();

	net_bibi();
	gui_state(msg);
}


char *net_myip(void)
{
	return iks_myip(net.parser);
}


void net_listen(void)
{
	http_listen();
	if(net.state == NET_OFF) return;
	iks_recv(net.parser, 0);
}


#ifdef NOMORPHOS
static void net_on_packet_gate(void);

static struct EmulLibEntry net_on_packet =
{
	TRAP_LIB, 0, (void (*)(void)) net_on_packet_gate
};

static void net_on_packet_gate(void)
{
	ULONG *lala = (ULONG *)REG_A7;
	void *udata = *lala++;
	ikspak *pak = *lala++;
#else
static void SAVEDS net_on_packet(void *udata, ikspak *pak)
{
#endif
	iks *x;
	if(!pak)
	{
		gui_state("Connection reset!");
		return;
	}
	
#ifdef DODEBUG
	{
		char errorMsg[100];
		#define PACKET_MSG "got packet: "
		
		sprintf(errorMsg, PACKET_MSG "type %d, ns %s", pak->type ? pak->type : "null", pak->ns ? pak->ns : "null");
		con_debug(errorMsg);
	}
#endif

	switch(pak->type)
	{
	case IKS_PAK_STREAM:
		net.streamid = iks_find_attrib(pak->x, "id");
		if(prf.auth_method) net.streamid = NULL;
		if(net.regflag)
		{
			iks *y;
			x = iks_make_iq(IKS_TYPE_SET, IKS_NS_REGISTER);
			iks_insert_attrib(x, "id", "reg");
			y = iks_child(x);
			iks_insert_cdata(iks_insert(y, "username"), net.id->user, -1);
			iks_insert_cdata(iks_insert(y, "password"), prf.pass, -1);
			iks_send(net.parser, x);
			iks_delete(x);
			net.state = NET_REG;
			gui_state("Registering...");
			break;
		}
		x = iks_make_auth(net.id, prf.pass, net.streamid);
		iks_insert_attrib(x, "id", "auth");
		iks_send(net.parser, x);
		iks_delete(x);
		net.state = NET_AUTH;
		gui_state("Logging in...");
		break;

	case IKS_PAK_MESSAGE:
		net_handle_msg(pak);
		break;

	case IKS_PAK_PRESENCE:
		if(gchat_packet(pak)) {
			con_debug("got unsupported groupchat packet");
			break;
		}
		roster_update_presence(pak);
		break;

	case IKS_PAK_S10N:
		presence_ask(pak);
		break;

	case IKS_PAK_IQ:
		net_handle_iq(pak);
		break;

	case IKS_PAK_ERROR:
		gui_state("Stream Error");
		break;

	default:
		con_debug("Unknown packet.");


		iks_delete(pak->x);
	}
}


static void net_handle_msg(ikspak *pak)
{
	juser u;
	jmessage *m;

	if(pak->subtype == IKS_TYPE_GROUPCHAT)
	{
		prf_event(EVT_GROUPCHAT);
		gchat_packet(pak);
		return;
	}

	if(pak->subtype == IKS_TYPE_CHAT)
	{
		prf_event(EVT_CHAT);
		chat_packet(pak);
		return;
	}

	u = roster_locate(pak->from);
	if(!u)
	{
		con_debug("cannot place user on roster!");
		return;
	}

	m = malloc(sizeof(jmessage));
	if(!m) return; /* FIXME */
	m->pak = pak;
	m->flags = 0;
	list_append(&u->msgs, m);

	prf_event(EVT_MESSAGE);

	if(u->readwin)
		DoMethod(u->readwin, READ_UPDATE);
	else
	{
		u->event = 1;
		roster_refresh(u);
	}


}


static void net_handle_iq(ikspak *pak)
{

	if(iks_strcmp(iks_find_attrib(pak->x, "id"), "auth") == 0)
	{
		if(pak->subtype == IKS_TYPE_RESULT)
		{
			iks *x;
			net.state = NET_FETCH;
			gui_state("Fetching roster...");
			agents_fetch();
			roster_fetch();
		}
		else
		{
			gui_state("Authorization failed!");
		}
		return;
	}

	else if(iks_strcmp(iks_find_attrib(pak->x, "id"), "reg") == 0)
	{
		if(pak->subtype == IKS_TYPE_RESULT)
		{
			iks *x;
			net.state = NET_AUTH;
			gui_state("Logging in...");
			x = iks_make_auth(net.id, prf.pass, net.streamid);
			iks_insert_attrib(x, "id", "auth");
			iks_send(net.parser, x);
			iks_delete(x);
		}
		else
		{
			gui_state("Registration failed!");
		}
		return;
	}
	
	if(iks_strcmp(pak->ns, IKS_NS_VERSION) == 0)
	{
		switch(pak->subtype)
		{
		case IKS_TYPE_GET:
		{
			iks *x, *y;
			x = iks_make_iq(IKS_TYPE_RESULT, IKS_NS_VERSION);
			iks_insert_attrib(x, "to", iks_id_print(pak->from));
			y = iks_find(x, "query");
			iks_insert_cdata(iks_insert(y, "name"), "Jabberwocky", 12);
			iks_insert_cdata(iks_insert(y, "version"), about_version(), -1);
			iks_insert_cdata(iks_insert(y, "os"), "AmigaOS", 7);
			iks_send(net.parser, x);
			iks_delete(x);
			return;
		}
		case IKS_TYPE_RESULT:
			userinfo_update(pak);
			return;
		}
	}

	if(iks_strcmp(pak->ns, IKS_NS_ROSTER) == 0)
	{
		roster_update(pak);
		return;
	}

	if(iks_strcmp(pak->ns, IKS_NS_AGENTS) == 0)
	{
		DoMethod(gui.agentswin, AGENTS_PARSE, pak);
		return;
	}

	if(iks_strcmp(pak->ns, IKS_NS_REGISTER) == 0)
	{
		register_this(pak);
		return;
	}

	if(iks_strcmp(pak->ns, IKS_NS_SEARCH) == 0)
	{
		search_display(pak);
		return;
	}

	if(iks_strcmp(pak->ns, IKS_NS_OOB) == 0)
	{
		xfer_packet(pak);
		return;
	}
	
	{
		char errorMsg[100];
		#define UNKNOWN_IQ_PACKET_MSG "unknown iq packet: "
		
		strcpy(errorMsg, UNKNOWN_IQ_PACKET_MSG);
		strncpy(errorMsg + strlen(UNKNOWN_IQ_PACKET_MSG), pak->ns, 99 - strlen(UNKNOWN_IQ_PACKET_MSG));
		errorMsg[100] = 0;
		con_debug(errorMsg);
	}
}


/*
		x = xmlnode_get_tag(p->x, "error");
		net_disconnect(xmlnode_get_data(xmlnode_get_firstchild(x)));
*/
