/*  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.
*/
/*
** preferences
*/

#include "common.h"

#include <MUI/NListview_mcc.h>
#include <libraries/asl.h>

#include "madthread.h"

static struct prfevent events[] =
{
	{ "Startup", "start", 0, NULL, NULL },
	{ "Exit", "quit", 0, NULL, NULL },
	{ "Connection Online", "online", 0, NULL, NULL },
	{ "Connection Offline", "offline", 0, NULL, NULL },
	{ "Incoming Message", "message", 0, NULL, NULL },
	{ "Incoming Chat Message", "chatmsg", 0, NULL, NULL },
	{ "Incoming Groupchat Message", "gcmsg", 0, NULL, NULL },
	{ NULL, 0, NULL },
	NULL
};

struct preferencesdata prf;

static ULONG prf_new(struct IClass *cl, Object *obj, struct opSet *msg);
static MUI_LIST_DISP_DECL(event_disp, struct prfevent *pe);
static void event_use(struct prefsdata *data);
static void event_set(struct prefsdata *data);
static void prf_use(struct prefsdata *data);
static void prf_set(struct prefsdata *data);
THREAD_DECL(runCommand);


void prf_setup(int argc, char *argv[])
{
	memset(&net, 0, sizeof(struct netdata));
	memset(&prf, 0, sizeof(struct preferencesdata));

	/* defaults */
	prf.http_port = 80;

	prf.events[EVT_ONLINE].sound = iks_strdup("PROGDIR:sounds/online.iff");
	prf.events[EVT_OFFLINE].sound = iks_strdup("PROGDIR:sounds/offline.iff");
	prf.events[EVT_MESSAGE].sound = iks_strdup("PROGDIR:sounds/message.iff");

	prf.logfile = iks_strdup(JABBERWOCKY_LOG);

	prf_load("PROGDIR:"JABBERWOCKY_PREFS);
}


void prf_event(int evt, ...)
{
	if(prf.events[evt].flags & PRFE_SHOW)
		set(gui.app, MUIA_Application_Iconified, FALSE);
		
	if (prf.events[evt].cmd) {
		mt_run(&runCommand, prf.events[evt].cmd, NULL);
	}
	
/*
	if(prf.events[evt].flags & PRFE_SCRPOPUP)
		DoMethod(win, MUIM_Window_ScreenToFront);
	if(prf.events[evt].flags & PRFE_WINPOPUP)
		DoMethod(win, MUIM_Window_ToFront);
*/


	sound_play(prf.events[evt].sound);
}


THREAD(runCommand)
{
	mthread *t;

	t = mt_start();
	if (!t) {
		con_debug("event command thread initialisation failed!\n");
		return;
	}
	
	Execute((char *) t->data, NULL, NULL);
	
	mt_end(t);
	return;
}
	
void prf_load(char *fname)
{
	iks *x, *y;
	int i;

	x = iks_load(fname);

	y = iks_child(iks_find(x, "events"));
	while(y)
	{
		if(iks_type(y) == IKS_TAG)
		{
			for(i=0; events[i].name; i++)
			{
				if(iks_strcmp(iks_name(y), events[i].tag) == 0)
				{
					prf.events[i].sound = iks_strdup(iks_find_attrib(y, "sound"));
					prf.events[i].cmd = iks_strdup(iks_find_attrib(y, "cmd"));
					if(iks_find_attrib(y, "show")) prf.events[i].flags |= PRFE_SHOW;
					if(iks_find_attrib(y, "winpop")) prf.events[i].flags |= PRFE_WINPOPUP;
					if(iks_find_attrib(y, "scrpop")) prf.events[i].flags |= PRFE_SCRPOPUP;
					break;
				}
			}
		}
		y = iks_next(y);
	}

	iks_delete(x);
}


void prf_save(char *fname)
{
	iks *x, *y, *z;
	int i;

	x = iks_new("jabberwocky");

	y = iks_insert(x, "events");
	for(i=0; events[i].name; i++)
	{
		z = iks_insert(y, events[i].tag);
		iks_insert_attrib(z, "sound", prf.events[i].sound);
		iks_insert_attrib(z, "cmd", prf.events[i].cmd);
		if(prf.events[i].flags & PRFE_SHOW) iks_insert_attrib(z, "show", "yes");
		if(prf.events[i].flags & PRFE_WINPOPUP) iks_insert_attrib(z, "winpop", "yes");
		if(prf.events[i].flags & PRFE_SCRPOPUP) iks_insert_attrib(z, "scrpop", "yes");
	}

	iks_save(fname, x);
	iks_delete(x);
}


void prf_load_account(void)
{
	iks *x;

	x = iks_load(JABBERWOCKY_ACCFILE);
	if(!x) return;
	prf.user = iks_strdup(iks_find_cdata(x, "jid"));
	prf.pass = iks_strdup(iks_find_cdata(x, "password"));
	if(prf.pass) prf.savepass = 1;
	iks_delete(x);
}


void prf_save_account(void)
{
	iks *x;

	x = iks_new("jabberwocky");
	if(prf.user) iks_insert_cdata(iks_insert(x, "jid"), prf.user, -1);
	if(prf.savepass && prf.pass)
		iks_insert_cdata(iks_insert(x, "password"), prf.pass, -1);

	iks_save(JABBERWOCKY_ACCFILE, x);

	iks_delete(x);
}


MUI_DISPATCH(prefs_dispatch)
{
	switch(msg->MethodID)
	{
	case OM_NEW:
		return prf_new(cl, obj, (APTR)msg);

	case PREFS_OPEN:
		prf_set(INST_DATA(cl,obj));
		set(obj, MUIA_Window_Open, TRUE);
		return 0;

	case PREFS_LASTSAVED:
		prf_load("PROGDIR:"JABBERWOCKY_PREFS);
/* fix me */
		return 0;

	case PREFS_SAVE:
		prf_use(INST_DATA(cl,obj));
		set(obj, MUIA_Window_Open, FALSE);
		prf_save("PROGDIR:"JABBERWOCKY_PREFS);
		return 0;

	case PREFS_USE:
		prf_use(INST_DATA(cl,obj));
		set(obj, MUIA_Window_Open, FALSE);
		return 0;

	case PREFS_CANCEL:
		set(obj, MUIA_Window_Open, FALSE);
		return 0;

	case PREFS_PAGE:
	{
		struct prefsdata *data = INST_DATA(cl,obj);
		u_long t;

		GetAttr(MUIA_NList_Active, data->pagelist, &t);
		if(t == -1) return(0);
		set(data->pagearea, MUIA_Group_ActivePage, t);

		return 0;
	}

	case PREFS_TESTSND:
	{
		struct prefsdata *data = INST_DATA(cl,obj);
		sound_play(mui_sget(data->sndstr));
		return 0;
	}

	case PREFS_ENTRY:
		event_use(INST_DATA(cl,obj));
		event_set(INST_DATA(cl,obj));
		return 0;

	}
	return DoSuperMethodA(cl, obj, msg);
}


static ULONG prf_new(struct IClass *cl, Object *obj, struct opSet *msg)
{
	static struct Hook dispHook = { {0,0}, &event_disp, NULL, NULL };
	static char *pages[] =
	{
		"General",
		"Locale",
		"Transfer",
		"Events",
		"Advanced",
		NULL
	};
	struct prefsdata *data;
	Object *pagelist, *pagearea, *savebut, *usebut, *canbut;
	Object *icontog, *autocontog, *recontog;
	Object *chartog, *isofilestr;
	Object *eventlist, *showtog, *wintog, *scrtog, *cmdstr, *sndstr, *testbut;
	Object *xintog, *xouttog, *debugtog, *logfilestr, *authtog;
	int i;

	obj = (Object *)DoSuperNew(cl, obj,
		MUIA_Window_ID, MAKE_ID('P','R','E','F'),
		MUIA_Window_Title, "Preferences",
		MUIA_HelpNode, "window-prefs",
		WindowContents, VGroup,
			Child, HGroup,
				Child, NListviewObject,
					MUIA_NListview_NList, pagelist = NListObject,
						InputListFrame,
						MUIA_ContextMenu, NULL,
						MUIA_NList_AdjustWidth, TRUE,
						MUIA_NList_SourceArray, pages,
						MUIA_CycleChain, 1,
					End,
				End,
				Child, pagearea = PageGroup,
					Child, VGroup,
						Child, MUI_MakeObject(MUIO_BarTitle, MSG_PRF_OPTIONS_TITLE),
						Child, mui_toggle("Start as iconified.", &icontog),
						Child, mui_toggle(MSG_PRF_AUTOCONNECT, &autocontog),
						Child, mui_toggle(MSG_PRF_RECONNECT, &recontog),
						Child, VSpace(0),
					End,
					Child, VGroup,
						Child, MUI_MakeObject(MUIO_BarTitle, MSG_PRF_CHARSET_TITLE),
						Child, mui_toggle("Internal (iso-8859-1)", &chartog),
						Child, HGroup,
							Child, Label2(MSG_PRF_CHARSET),
							Child, isofilestr = PopaslObject,
								MUIA_Popstring_String, StringObject,
									StringFrame,
									MUIA_String_MaxLen, 256,
									MUIA_CycleChain, 1,
								End,
								MUIA_Popstring_Button, PopButton(MUII_PopFile),
								MUIA_Popasl_Type, ASL_FileRequest,
							End,
						End,
						Child, TextObject,
							TextFrame,
							MUIA_Background, MUII_TextBack,
							MUIA_Text_PreParse, "\33c",
						End,
						Child, VSpace(0),
					End,
					Child, VGroup,
						Child, HGroup,
							Child, Label2(MSG_PRF_XFER_PORT),
							Child, StringObject,
								StringFrame,
								MUIA_String_Accept, "0123456789",
								MUIA_String_MaxLen, 6,
								MUIA_CycleChain, 1,
							End,
						End,
						Child, VSpace(0),
					End,
					Child, VGroup,
						Child, NListviewObject,
							MUIA_NListview_NList, eventlist = NListObject,
								InputListFrame,
								MUIA_ContextMenu, NULL,
								MUIA_NList_DisplayHook, &dispHook,
								MUIA_CycleChain, 1,
							End,
						End,
						Child, HGroup,
							Child, mui_toggle("Window Popup", &wintog),
							Child, mui_toggle("Screen Popup", &scrtog),
							Child, mui_toggle("Deiconify", &showtog),
						End,
						Child, ColGroup(2),
							Child, Label2(MSG_PRF_COMMAND),
							Child, cmdstr = PopaslObject,
								MUIA_Popstring_String, StringObject,
									StringFrame,
									MUIA_String_MaxLen, 256,
									MUIA_CycleChain, 1,
								End,
								MUIA_Popstring_Button, PopButton(MUII_PopFile),
								MUIA_Popasl_Type, ASL_FileRequest,
							End,
							Child, Label2(MSG_PRF_SOUND),
							Child, HGroup,
								Child, sndstr = PopaslObject,
									MUIA_HorizWeight, 300,
									MUIA_Popstring_String, StringObject,
										StringFrame,
										MUIA_String_MaxLen, 256,
										MUIA_CycleChain, 1,
									End,
									MUIA_Popstring_Button, PopButton(MUII_PopFile),
									MUIA_Popasl_Type, ASL_FileRequest,
								End,
								Child, testbut = mui_button(MSG_PRF_SOUNDTEST_GAD),
							End,
						End,
					End,
					Child, VGroup,
						Child, mui_toggle("Send plaintext passwords.", &authtog),
						Child, MUI_MakeObject(MUIO_BarTitle, MSG_PRF_LOG_TITLE),
						Child, HGroup,
							Child, mui_toggle("Incoming XML", &xintog),
							Child, mui_toggle("Outgoing XML", &xouttog),
							Child, mui_toggle("Debug", &debugtog),
						End,
						Child, HGroup,
							Child, Label2(MSG_PRF_LOGFILE),
							Child, logfilestr = PopaslObject,
								MUIA_Popstring_String, StringObject,
									StringFrame,
									MUIA_String_MaxLen, 256,
									MUIA_CycleChain, 1,
								End,
								MUIA_Popstring_Button, PopButton(MUII_PopFile),
								MUIA_Popasl_Type, ASL_FileRequest,
							End,
						End,
						Child, VSpace(0),
					End,
				End,
			End,
			Child, RectangleObject,
				MUIA_FixHeightTxt, "M",
				MUIA_Rectangle_HBar, TRUE,
			End,
			Child, HGroup,
				Child, savebut = mui_button(MSG_PRF_SAVE_GAD),
				Child, usebut = mui_button(MSG_PRF_USE_GAD),
				Child, canbut = mui_button(MSG_PRF_CANCEL_GAD),
			End,
		End,
		TAG_MORE, msg->ops_AttrList);

	if(!obj) return(0);

	for(i=0; events[i].name; i++)
	{
		DoMethod(eventlist, MUIM_NList_InsertSingle, &events[i], MUIV_NList_Insert_Bottom);
	}

	data = INST_DATA(cl,obj);
	data->pagelist = pagelist;
	data->pagearea = pagearea;
	data->icontog = icontog;
	data->autocontog = autocontog;
	data->eventlist = eventlist;
	data->showtog = showtog;
	data->wintog = wintog;
	data->scrtog = scrtog;
	data->cmdstr = cmdstr;
	data->sndstr = sndstr;
	data->authtog = authtog;
	data->logfilestr = logfilestr;
	data->xintog = xintog;
	data->xouttog = xouttog;
	data->debugtog = debugtog;
	data->lastitem = -1;



	DoMethod(eventlist, MUIM_Notify, MUIA_NList_Active, MUIV_EveryTime, obj, 1, PREFS_ENTRY);
	DoMethod(testbut, MUIM_Notify, MUIA_Pressed, FALSE, obj, 1, PREFS_TESTSND);

	DoMethod(pagelist, MUIM_Notify, MUIA_NList_Active, MUIV_EveryTime, obj, 1, PREFS_PAGE);
	DoMethod(savebut, MUIM_Notify, MUIA_Pressed, FALSE, obj, 1, PREFS_SAVE);
	DoMethod(usebut, MUIM_Notify, MUIA_Pressed, FALSE, obj, 1, PREFS_USE);
	DoMethod(canbut, MUIM_Notify, MUIA_Pressed, FALSE, obj, 1, PREFS_CANCEL);
	DoMethod(obj, MUIM_Notify, MUIA_Window_CloseRequest, TRUE, obj, 1, PREFS_CANCEL);

	return (ULONG)obj;
}


MUI_LIST_DISP_STATIC(event_disp, struct prfevent *pe)
{
	*array = pe->name;
	if(pe->flags & PRFE_CHANGED)
		array[DISPLAY_ARRAY_MAX] = "\33b";

	return 0;
}


static void event_use(struct prefsdata *data)
{
	u_long t, t2;

	t = data->lastitem;
	if(t != MUIV_NList_Active_Off)
	{
		if(events[t].sound) free(events[t].sound);
		events[t].sound = iks_strdup(mui_sget(data->sndstr));
		if(events[t].cmd) free(events[t].cmd);
		events[t].cmd = iks_strdup(mui_sget(data->cmdstr));
		GetAttr(MUIA_Selected, data->showtog, &t2);
		if(t2) events[t].flags |= PRFE_SHOW; else events[t].flags &= (~PRFE_SHOW);
		GetAttr(MUIA_Selected, data->wintog, &t2);
		if(t2) events[t].flags |= PRFE_WINPOPUP; else events[t].flags &= (~PRFE_WINPOPUP);
		GetAttr(MUIA_Selected, data->scrtog, &t2);
		if(t2) events[t].flags |= PRFE_SCRPOPUP; else events[t].flags &= (~PRFE_SCRPOPUP);
	}
	GetAttr(MUIA_NList_Active, data->eventlist, &t);
	data->lastitem = t;
}


static void event_set(struct prefsdata *data)
{
	u_long t, i;

	GetAttr(MUIA_NList_Active, data->eventlist, &t);
	if(t != MUIV_NList_Active_Off)
	{
		set(data->cmdstr, MUIA_String_Contents, events[t].cmd);
		set(data->sndstr, MUIA_String_Contents, events[t].sound);
		if(events[t].flags & PRFE_SHOW) i = TRUE; else i = FALSE;
		set(data->showtog, MUIA_Selected, i);
		if(events[t].flags & PRFE_WINPOPUP) i = TRUE; else i = FALSE;
		set(data->wintog, MUIA_Selected, i);
		if(events[t].flags & PRFE_SCRPOPUP) i = TRUE; else i = FALSE;
		set(data->scrtog, MUIA_Selected, i);
	}
}


#define USE_FLAG(x,y,z) \
	GetAttr(MUIA_Selected, x , &t); \
	if(t) y |= z ; else y &= (~ z )

static void prf_use(struct prefsdata *data)
{
	u_long t;
	int i;

	event_use(data);
	for(i=0; events[i].name; i++)
	{
		prf.events[i].sound = iks_strdup(events[i].sound);
		prf.events[i].cmd = iks_strdup(events[i].cmd);
		prf.events[i].flags = events[i].flags;
	}

	prf.logfile = iks_strdup(mui_sget(data->logfilestr));
	USE_FLAG(data->xintog, prf.logflags, 1);
	USE_FLAG(data->xouttog, prf.logflags, 2);
	USE_FLAG(data->debugtog, prf.logflags, 4);

	USE_FLAG(data->authtog, prf.auth_method, 1);

	USE_FLAG(data->icontog, prf.options, 1);
	USE_FLAG(data->autocontog, prf.options, 2);
}


#define SET_FLAG(x,y,z) \
	if( y & z ) t = TRUE; else t = FALSE; \
	set( x , MUIA_Selected, t );

static void prf_set(struct prefsdata *data)
{
	u_long t;
	int i;

	for(i=0; events[i].name; i++)
	{
		events[i].sound = iks_strdup(prf.events[i].sound);
		events[i].cmd = iks_strdup(prf.events[i].cmd);
		events[i].flags = prf.events[i].flags;
	}
	event_set(data);

	set(data->logfilestr, MUIA_String_Contents, prf.logfile);
	SET_FLAG(data->xintog, prf.logflags, 1);
	SET_FLAG(data->xouttog, prf.logflags, 2);
	SET_FLAG(data->debugtog, prf.logflags, 4);

	SET_FLAG(data->authtog, prf.auth_method, 1);

	SET_FLAG(data->icontog, prf.options, 1);
	SET_FLAG(data->autocontog, prf.options, 2);
}
