/*
** Amster - Main GUI
** Copyright © 1999-2001 by Gürer Özen
** Copyright © 2000-2001 by Jacob Laursen
**
** 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
*/

#include "amster.h"

#include <exec/memory.h>

#include <proto/asl.h>
#include <proto/dos.h>
#include <proto/icon.h>
#include <proto/locale.h>
#include <proto/utility.h>

#include <libraries/gadtools.h>
#include <libraries/asl.h>

#include <MUI/Lamp_mcc.h>
#include <MUI/NListview_mcc.h>
#include <MUI/textinput_mcc.h>

#include "chatline.h"
#include "url.h"
#include "amster_Cat.h"

struct Library *MUIMasterBase = NULL;
struct LocaleBase *LocaleBase = NULL;

int UseLamps = 0;
int UseTWF = 0;
struct guidata mygui;
struct guidata *gui = &mygui;
enum OnlineState gui_onlinestate = OFFLINE;
listener l;

void gui_free(void);
int gui_setup(void);
MUI_HOOK_DECL(gui_handle, Object *app, u_long *id);
void gui_about(void);
void gui_appicon(int t);

struct Hook handleHook = {{0, 0}, &gui_handle, NULL, NULL};

static muiclass amster_mccs[] =
{
	{ MUIC_Text, sizeof(struct urldata), &url_dispatch, &mygui.url_mcc },
	{ MUIC_String, sizeof(struct chatlinedata), &chatline_dispatch, &mygui.chatline_mcc },
	{ MUIC_Group, sizeof(struct paneldata), &panel_dispatch, &mygui.panel_mcc },
	{ MUIC_Group, sizeof(struct searchdata), &search_dispatch, &mygui.search_mcc },
	{ MUIC_Group, sizeof(struct resultdata), &resultview_dispatch, &mygui.resultview_mcc },
	{ MUIC_Window, sizeof(struct TransferData), &dl_dispatch, &mygui.dl_mcc },
	{ MUIC_Window, sizeof(struct TransferData), &ul_dispatch, &mygui.ul_mcc },
	{ MUIC_Window, sizeof(struct shdata), &share_dispatch, &mygui.share_mcc },
	{ MUIC_Window, sizeof(struct prfdata), &prf_dispatch, &mygui.prf_mcc },
	{ MUIC_Window, sizeof(struct infodata), &info_dispatch, &mygui.info_mcc },
	{ MUIC_Window, 0, &about_dispatch, &mygui.about_mcc },
	{ MUIC_Window, sizeof(struct msgdata), &msg_dispatch, &mygui.msg_mcc },
	{ MUIC_Window, sizeof(struct chatdata), &chat_dispatch, &mygui.chat_mcc },
	{ MUIC_Window, sizeof(struct NavigatorData), &NavigatorDispatch, &mygui.navi_mcc },
	{ MUIC_Window, sizeof(struct HotlistData), &HotlistDispatch, &mygui.hotlist_mcc },
	{ MUIC_Window, sizeof(struct ChannelListData), &ChannelListDispatch, &mygui.channellist_mcc },

	{ NULL, 0, NULL, NULL }
};


void gui_run(unsigned long tcpsig)
{
	ULONG sigs=0;

	memset(gui, 0, sizeof(struct guidata));
	if (gui_setup()) {
		prf_event(PRFE_STARTUP);
		DoMethod(gui->shwin, SHARE_LOAD);
		while (1) {
			while (DoMethod(gui->app, MUIM_Application_NewInput, &sigs) != MUIV_Application_ReturnID_Quit) {
				if (sigs) {
					sigs = Wait(sigs | SIGBREAKF_CTRL_C | tcpsig | th_sigmask);
					if (sigs & SIGBREAKF_CTRL_C) break;
					if (sigs & tcpsig) nap_listen();
					if (sigs & th_sigmask) th_poll();
				}
			}
			if (!dl_count && !ul_count) break;
			if ((dl_count || ul_count) && MUI_Request(gui->app, gui->win, 0L,
									   (char *)MSG_REALLYQUIT_TITLE,
									   (char *)MSG_REALLYQUIT_GAD,
									   (char *)MSG_REALLYQUIT)) break;
		}
		prf_event(PRFE_EXIT);
		if (prf->autosave && sharechanged) DoMethod(gui->shwin, SHARE_SAVE);
		if (prf->ServerList > 0 && ServerListChanged) DoMethod(gui->WI_Navigator, NAVI_SAVE);
		if (HotlistChanged) DoMethod(gui->WI_Hotlist, HOTLIST_SAVE);
		if (gui_onlinestate > OFFLINE) nap_logout();
#ifdef AMSTER_DEBUG
		if (l && l->t) Signal(l->t->task, SIGBREAKF_CTRL_F);
#endif
	}
	th_exit();
	gui_free();
}


void gui_free(void)
{
	gui_appicon(-1);
	if (gui->app) MUI_DisposeObject(gui->app);
	lamp_dispose();
    if (QueueClass) MUI_DeleteCustomClass(QueueClass);
	if (ResultviewContext) MUI_DeleteCustomClass(ResultviewContext);
	if (UserlistContext) MUI_DeleteCustomClass(UserlistContext);
	mui_classes_cleanup(amster_mccs);
	if (locale) CloseLocale(locale);
	if (LocaleBase) CloseLibrary((struct Library *)LocaleBase);
	if (MUIMasterBase) CloseLibrary(MUIMasterBase);
}


int gui_setup(void)
{
	long winopen;
	u_long *MI_Navigator, *MI_Connect, *MI_ConnectTo, *MI_Reconnect, *MI_Disconnect;
	u_long *aboutmenu, *muimenu, *helpmenu, *hidemenu, *quitmenu;
	u_long *MI_Open, *MI_Merge, *MI_Save, *MI_SaveAs;
	u_long *debugmenu, *dlmenu, *ulmenu, *sharemenu, *usermenu, *chatmenu, *MI_Hotlist;
	u_long *muiprfmenu, *prfmenu, *MI_LastSaved, *saveprfmenu;
	u_long *rxexemenu;

	struct Library *NListBase;
	struct Library *LampBase;
	struct Library *TWFBase;
	struct Library *TextinputBase;

	localize_array(nap_linktype);

	MUIMasterBase = OpenLibrary(MUIMASTER_NAME, MUIMASTER_VMIN);
	if (!MUIMasterBase) {
		printf(MSG_NO_LIBRARY, MUIMASTER_NAME, MUIMASTER_VMIN);
		return(0);
	}

	LocaleBase = (struct LocaleBase *)OpenLibrary("locale.library", 37L);
	if (!LocaleBase) {
		printf(MSG_NO_LIBRARY, "locale.library", 37);
		return(0);
	}
	locale = OpenLocale(NULL);

	NListBase = OpenLibrary("LIBS:MUI/NList.mcc", 19);
	if (!NListBase) {
		printf(MSG_NO_LIBRARY, "NList.mcc", 19);
		return(0);
	}
	if (NListBase->lib_Version == 19 && NListBase->lib_Revision < 97) {
		printf(MSG_NO_LIBRARY, "NList.mcc", 19);
		CloseLibrary(NListBase);
		return(0);
	}
	CloseLibrary(NListBase);

	TextinputBase = OpenLibrary("LIBS:MUI/Textinput.mcc", 26);
	if (!TextinputBase) {
		printf(MSG_NO_LIBRARY, "Textinput.mcc", 26);
		return(0);
	}
	CloseLibrary(TextinputBase);

	LampBase = OpenLibrary("LIBS:MUI/Lamp.mcc", 11);
	if (LampBase) {
		if (!(LampBase->lib_Version == 11 && LampBase->lib_Revision == 0))
			UseLamps = 1;
		CloseLibrary(LampBase);
	}
	TWFBase = OpenLibrary("LIBS:MUI/TWFmultiLED.mcc", 12);
	if (TWFBase) {
		if (!(TWFBase->lib_Version == 12 && TWFBase->lib_Revision < 6))
			UseTWF = 1;
		CloseLibrary(TWFBase);
	}

	if (!prf_load("ENV:"AMSTER_PREFS)) prf_load("ENVARC:"AMSTER_PREFS);

#ifdef AMSTER_DEBUG
	if (prf->port) {
		l = malloc(sizeof(_listener));
		if (l) {
			memset(l, 0, sizeof(_listener));
			l->t = th_spawn(ListenerMsgHandler, "Amster listener", &createlistener, 0, l);
		}
	}
#endif

	lamp_create();

	if (!(ResultviewContext = MUI_CreateCustomClass(NULL, MUIC_NList, NULL, sizeof(struct ResultviewContextData), &ResultviewContextDispatcher))) return 0;
	if (!(UserlistContext = MUI_CreateCustomClass(NULL, MUIC_NList, NULL, sizeof(struct UserlistContextData), &UserlistContextDispatcher))) return 0;

	if(!mui_classes_setup(amster_mccs)) return(0);

	gui->iconpanel = NewObject(gui->panel_mcc->mcc_Class, NULL, TAG_DONE);
	gui->rect = NULL;

	gui->app = ApplicationObject,
		MUIA_Application_Title,       "Amster",
#ifdef AMSTER_DEBUG
		MUIA_Application_Version,     "$VER: Amster "AMSTER_VERSION" ("AMSTER_DATE") Build #"AMSTER_BUILD,
#else
		MUIA_Application_Version,     "$VER: Amster "AMSTER_VERSION" ("AMSTER_DATE")",
#endif
        MUIA_Application_Author,      "Jacob Laursen",
		MUIA_Application_Description, MSG_CX_DESCRIPTION,
		MUIA_Application_Base,        "AMSTER",
		MUIA_Application_Commands,    &rexx_cmds,
		MUIA_Application_HelpFile,    AMSTER_HELP,
		MUIA_Application_Menustrip,   MenustripObject,
			Child, MenuObject,
				MUIA_Menu_Title, MSG_AMSTER_MENU,
				Child, MI_Navigator = makemenu(MSG_AMSTER_NAVIGATOR),
				Child, makemenu(NULL),
				Child, MI_Connect = makemenu(MSG_AMSTER_CONNECT),
				Child, MI_ConnectTo = makemenu(MSG_AMSTER_CONNECTTO),
				Child, MI_Reconnect = makemenu(MSG_AMSTER_RECONNECT),
				Child, MI_Disconnect = makemenu(MSG_AMSTER_DISCONNECT),
				Child, makemenu(NULL),
				Child, aboutmenu = makemenu(MSG_AMSTER_ABOUT),
				Child, muimenu = makemenu(MSG_AMSTER_ABOUTMUI),
				Child, helpmenu = makemenu(MSG_AMSTER_HELP),
				Child, makemenu(NULL),
				Child, hidemenu = makemenu(MSG_AMSTER_HIDE),
				Child, quitmenu = makemenu(MSG_AMSTER_QUIT),
			End,
			Child, MenuObject,
				MUIA_Menu_Title, MSG_PROJECT_MENU,
				Child, MI_Open   = makemenu(MSG_PROJECT_OPEN),
				Child, MI_Merge  = makemenu(MSG_PROJECT_MERGE),
				Child, MI_Save   = makemenu(MSG_PROJECT_SAVE),
				Child, MI_SaveAs = makemenu(MSG_PROJECT_SAVEAS),
			End,
			Child, MenuObject,
				MUIA_Menu_Title, MSG_WINDOWS_MENU,
				Child, debugmenu = makemenu(MSG_WINDOWS_DEBUG),
				Child, sharemenu = makemenu(MSG_WINDOWS_SHARE),
				Child, dlmenu = makemenu(MSG_WINDOWS_DOWNLOAD),
				Child, ulmenu = makemenu(MSG_WINDOWS_UPLOAD),
				Child, usermenu = makemenu(MSG_WINDOWS_USER),
				Child, chatmenu = makemenu(MSG_WINDOWS_CHAT),
				Child, MI_Hotlist = makemenu(MSG_WINDOWS_HOTLIST),
			End,
			Child, MenuObject,
				MUIA_Menu_Title, MSG_SETTINGS_MENU,
				Child, gui->iconpanelmenu = maketmenu(MSG_SETTINGS_ICONPANEL),
				Child, makemenu(NULL),
				Child, muiprfmenu = makemenu(MSG_SETTINGS_MUI),
				Child, prfmenu = makemenu(MSG_SETTINGS_CONFIG),
				Child, makemenu(NULL),
				Child, MI_LastSaved = makemenu(MSG_SETTINGS_LASTSAVED),
				Child, saveprfmenu = makemenu(MSG_SETTINGS_SAVE),
			End,
			Child, MenuObject,
				MUIA_Menu_Title, MSG_AREXX_MENU,
				Child, rxexemenu = makemenu(MSG_AREXX_EXECUTE),
			End,
		End,

		SubWindow, gui->win = WindowObject,
		MUIA_Window_ID, MAKE_ID('M','A','I','N'),
		MUIA_Window_Title, "Amster v"AMSTER_VERSION,
		WindowContents, gui->maingrp = HGroup,
			Child, VGroup,
				Child, gui->searchpanel = NewObject(gui->search_mcc->mcc_Class, NULL, TAG_DONE),
				Child, RectangleObject,
					MUIA_FixHeight, 8,
					MUIA_Rectangle_HBar, TRUE,
				End,
				Child, gui->statgrp = HGroup,
					Child, gui->stat = TextObject,
						TextFrame,
						MUIA_Background, MUII_TextBack,
						MUIA_Text_PreParse, "\33c",
					End,
				End,
				Child, HGroup,
					Child, gui->inbut  = SimpleButton(MSG_CONNECT_GAD),
					Child, gui->outbut = SimpleButton(MSG_DISCONNECT_GAD),
					Child, gui->rebut  = SimpleButton(MSG_RECONNECT_GAD),
				End,
			End,
/*
			Child, gui->rect = HGroup,
				Child, RectangleObject,
					MUIA_FixWidth, 4,
					MUIA_Rectangle_VBar, TRUE,
				End,
				Child, gui->iconpanel = NewObject(gui->panel_mcc->mcc_Class, NULL, TAG_DONE),
			End,
*/
		End,
		End,

		SubWindow, gui->WI_ConnectTo = WindowObject,
		MUIA_HelpNode, "connectto",
		MUIA_Window_Title, MSG_CONNECTTO_TITLE,
		MUIA_Window_ID, MAKE_ID('C','O','N','N'),
		WindowContents, VGroup,
			Child, HGroup,
				Child, ColGroup(2),
					Child, Label2(MSG_CONNECTTO_SERVER),
					Child, HGroup,
						Child, gui->ST_ConnectServer = TextinputObject,
							StringFrame,
                            MUIA_Textinput_Multiline, FALSE,
							MUIA_String_AdvanceOnCR, TRUE,
							MUIA_String_Accept, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-",
							MUIA_CycleChain, 1,
						End,
						Child, Label2(MSG_CONNECTTO_PORT),
						Child, gui->ST_ConnectPort = TextinputObject,
							StringFrame,
                            MUIA_Textinput_Multiline, FALSE,
							MUIA_String_AdvanceOnCR, TRUE,
							MUIA_HorizWeight, 45,
							MUIA_String_Accept, "0123456789",
							MUIA_String_MaxLen, 6,
							MUIA_CycleChain, 1,
						End,
					End,
					Child, Label2(MSG_CONNECTTO_USERNAME),
					Child, gui->ST_ConnectUser = TextinputObject,
						StringFrame,
                        MUIA_Textinput_Multiline, FALSE,
						MUIA_String_Reject, ":%$ ",
						MUIA_String_AdvanceOnCR, TRUE,
						MUIA_CycleChain, 1,
					End,
					Child, Label2(MSG_CONNECTTO_PASSWORD),
					Child, gui->ST_ConnectPw = StringObject,
						StringFrame,
						MUIA_String_Reject, " ",
						MUIA_String_AdvanceOnCR, TRUE,
						MUIA_String_Secret, TRUE,
						MUIA_CycleChain, 1,
					End,
				End,
			End,
			Child, maketoggle(MSG_CONNECTTO_REG, &gui->TG_ConnectReg),
			Child, gui->BT_ConnectServer = SimpleButton(MSG_CONNECTTO_CONNECT_GAD),
		End,
		End,

		SubWindow, gui->awin = NewObject(gui->about_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->swin = NewObject(gui->prf_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->iwin = NewObject(gui->info_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->dwin = NewObject(gui->dl_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->uwin = NewObject(gui->ul_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->shwin = NewObject(gui->share_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->mwin = NewObject(gui->msg_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->WI_Navigator = NewObject(gui->navi_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->WI_Hotlist = NewObject(gui->hotlist_mcc->mcc_Class, NULL, TAG_DONE),
		SubWindow, gui->WI_ChannelList = NewObject(gui->channellist_mcc->mcc_Class, NULL, TAG_DONE),

	End;

	if (!gui->app) {
		printf(MSG_APP_ERROR);
		return(0);
	}

	DoMethod(gui->inbut,MUIM_Notify,MUIA_Pressed,FALSE,gui->app,3,MUIM_CallHook,&handleHook, CONNECT);
	DoMethod(gui->outbut,MUIM_Notify,MUIA_Pressed,FALSE,gui->app,3,MUIM_CallHook,&handleHook, DISCONNECT);
	DoMethod(gui->rebut,MUIM_Notify,MUIA_Pressed,FALSE,gui->app,3,MUIM_CallHook,&handleHook, RECONNECT);

	DoMethod(gui->iconpanelmenu, MUIM_Notify, MUIA_Menuitem_Checked, MUIV_EveryTime, gui->app, 3, MUIM_CallHook, &handleHook, UPDATEPANEL);

	DoMethod(MI_Navigator, MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->WI_Navigator, 3, MUIM_Set, MUIA_Window_Open, TRUE);
	DoMethod(MI_Connect, MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->app, 3, MUIM_CallHook, &handleHook, CONNECT);
	DoMethod(MI_ConnectTo, MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->WI_ConnectTo, 3, MUIM_Set, MUIA_Window_Open, TRUE);
	DoMethod(MI_Reconnect, MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->app, 3, MUIM_CallHook, &handleHook, RECONNECT);
	DoMethod(MI_Disconnect, MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->app, 3, MUIM_CallHook, &handleHook, DISCONNECT);
	DoMethod(gui->WI_ConnectTo, MUIM_Notify, MUIA_Window_CloseRequest, TRUE, gui->WI_ConnectTo, 3, MUIM_Set, MUIA_Window_Open, FALSE);

	/* Connect to... */

	DoMethod(gui->BT_ConnectServer, MUIM_Notify, MUIA_Pressed, FALSE, gui->app, 3, MUIM_CallHook, &handleHook, CONNECTSERVER);

	/* Pulldown menu */

	DoMethod(aboutmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->awin,3,MUIM_Set,MUIA_Window_Open,TRUE);
	DoMethod(muimenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->app,2,MUIM_Application_AboutMUI,gui->win);
	DoMethod(helpmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->app,5,MUIM_Application_ShowHelp,gui->win,AMSTER_HELP,0,0);
	DoMethod(hidemenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->app,3,MUIM_Set,MUIA_Application_Iconified,TRUE);
	DoMethod(quitmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->app,2,MUIM_Application_ReturnID,MUIV_Application_ReturnID_Quit);

	DoMethod(MI_Open,   MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->shwin, 2, SHARE_LOADAS, 0);
	DoMethod(MI_Merge,  MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->shwin, 2, SHARE_LOADAS, 1);
	DoMethod(MI_Save,   MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->shwin, 1, SHARE_SAVE);
	DoMethod(MI_SaveAs, MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->shwin, 1, SHARE_SAVEAS);

	DoMethod(debugmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->iconpanel,1,PANEL_OPENDEBUG);
	DoMethod(dlmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->iconpanel,1,PANEL_OPENDL);
	DoMethod(ulmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->uwin,1,UPLOAD_OPEN);
	DoMethod(sharemenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->iconpanel,1,PANEL_OPENSHARE);
	DoMethod(usermenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->iconpanel,1,PANEL_OPENMSG);
	DoMethod(chatmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->iconpanel,1,PANEL_NEWCHAT);
	DoMethod(MI_Hotlist, MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->WI_Hotlist, 3, MUIM_Set, MUIA_Window_Open, TRUE);

	DoMethod(muiprfmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->app,2,MUIM_Application_OpenConfigWindow,0);
	DoMethod(prfmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->iconpanel,1,PANEL_OPENPRF);
	DoMethod(MI_LastSaved, MUIM_Notify, MUIA_Menuitem_Trigger, MUIV_EveryTime, gui->swin, 1, PRF_LASTSAVED);
	DoMethod(saveprfmenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->swin,1,PRF_SAVEALL);

	DoMethod(rxexemenu,MUIM_Notify,MUIA_Menuitem_Trigger,MUIV_EveryTime,gui->app,3,MUIM_CallHook,&handleHook, EXECUTEAREXX);

	DoMethod(gui->win,MUIM_Notify,MUIA_Window_CloseRequest,TRUE,gui->app,2,MUIM_Application_ReturnID,MUIV_Application_ReturnID_Quit);
	DoMethod(gui->app, MUIM_Notify, MUIA_Application_Iconified, FALSE, gui->app,3, MUIM_CallHook, &handleHook, DEICONIFIED);

	if (UseLamps) DoMethod(gui->statgrp, OM_ADDMEMBER, gui->lamp = LampObject, MUIA_Lamp_Type, MUIV_Lamp_Type_Huge, MUIA_Lamp_Color, MUIV_Lamp_Color_Off, End);

	DoMethod(gui->searchpanel, SEARCH_SET);

	set(gui->ST_ConnectUser, MUIA_String_Contents, prf->user);
	set(gui->ST_ConnectPw,   MUIA_String_Contents, prf->pass);
	set(gui->TG_ConnectReg,  MUIA_Selected,        TRUE);

	if (prf->noiconpanel) {
		set(gui->iconpanelmenu, MUIA_Menuitem_Checked, FALSE);
/*		set(gui->rect, MUIA_ShowMe, FALSE);*/
	}
	else {
		set(gui->iconpanelmenu, MUIA_Menuitem_Checked, TRUE);
	}

	gui_appicon(0);
	gui_state(OFFLINE);

	if (!UseLamps) gui_debug((char *)MSG_INFO_NOLAMPS);

	/* Set screen title for all windows */
	DoMethod(gui->app, MUIM_MultiSet, MUIA_Window_ScreenTitle,
		"Amster "AMSTER_VERSION" ("AMSTER_DATE") © 1999-2001 Gürer Özen & Jacob Laursen",
		gui->win, gui->awin, gui->swin, gui->shwin, gui->mwin, gui->iwin,
		gui->dwin, gui->uwin, gui->WI_ConnectTo, gui->WI_Navigator,
		gui->WI_Hotlist, gui->WI_ChannelList, NULL);

	set(gui->win, MUIA_Window_Open, TRUE);
	get(gui->win, MUIA_Window_Open, &winopen);
	if (!winopen) {
		printf(MSG_ERR_NOWINDOW);
		return(0);
	}

	if (!prf->user) DoMethod(gui->iconpanel, PANEL_OPENPRF);
	/* If no account is configured, open configuration window */

	if (prf->user && prf->autocon) {
		nap_login();
		return(1);
	}

	set(gui->stat, MUIA_Text_Contents, MSG_STATUS2_NOTCONNECTED);
	return(1);
}


MUI_HOOK(gui_handle, Object *app, u_long *id)
{
	u_long tmp;
	char *buf;

	switch(*id) {
		case CONNECT:
			if (gui_onlinestate < CONNECTING) nap_login();
			break;
		case DISCONNECT:
			nap_logout();
			set(gui->stat, MUIA_Text_Contents, MSG_STATUS2_NOTCONNECTED);
			break;
		case RECONNECT:
			if (gui_onlinestate > OFFLINE) nap_logout();
			nap_login();
			break;
		case CONNECTSERVER:
			{
			int port;

			if (gui_onlinestate > OFFLINE) nap_logout();
			get(gui->ST_ConnectServer, MUIA_String_Contents, &buf);
			get(gui->ST_ConnectPort,   MUIA_String_Integer,  &tmp);
			port = (int)tmp;
			get(gui->ST_ConnectUser,   MUIA_String_Contents, &gui->ConnectUser);
			get(gui->ST_ConnectPw,     MUIA_String_Contents, &gui->ConnectPw);
			get(gui->TG_ConnectReg,    MUIA_Selected,        &tmp);
			set(gui->WI_ConnectTo, MUIA_Window_Open, FALSE);
			if (tmp) prf->regflag = 2;
			else prf->regflag = 0;

			nap_login_fromlist(buf, port);

			break;
			}
		case EXECUTEAREXX:
			{
			BPTR lock;
			struct FileRequester *freq;
			u_long win;
			char DefaultDir[256] = "";

			lock = Lock("PROGDIR:Rexx/", ACCESS_READ);
			if (lock) {
				NameFromLock(lock, DefaultDir, 255);
				UnLock(lock);
			}

			get(gui->win, MUIA_Window_Window, &win);
			freq = AllocAslRequestTags(ASL_FileRequest, TAG_DONE);
			if (!freq) break;
			tmp = AslRequestTags(freq,
				ASLFR_Window, win,
				ASLFR_TitleText, MSG_SELECTRX_TITLE,
				ASLFR_InitialDrawer, DefaultDir,
				ASLFR_DoSaveMode, FALSE,
				TAG_DONE);
			if (tmp) {
				static char buf[512];
				strcpy(buf, freq->fr_Drawer);
				AddPart(buf, freq->fr_File,511);
				rexx_execute(buf, NULL);
			}
			FreeAslRequest(freq);
			break;
			}
		case UPDATEPANEL:
			GetAttr(MUIA_Menuitem_Checked, gui->iconpanelmenu, &tmp);
			if (tmp==TRUE) {
				if (!gui->rect && DoMethod(gui->maingrp, MUIM_Group_InitChange)) {
					DoMethod(gui->maingrp, OM_ADDMEMBER,
						gui->rect = HGroup,
							Child, RectangleObject,
								MUIA_FixWidth, 4,
								MUIA_Rectangle_VBar, TRUE,
							End,
							Child, gui->iconpanel,
						End);
					DoMethod(gui->maingrp, MUIM_Group_ExitChange);
				}
			}
			else {
				if (gui->rect && DoMethod(gui->maingrp, MUIM_Group_InitChange)) {
					DoMethod(gui->maingrp, OM_REMMEMBER, gui->rect);
					DoMethod(gui->maingrp, MUIM_Group_ExitChange);
/*					DisposeObject(gui->rect);*/
					gui->rect = NULL;
				}
			}
			break;
		case DEICONIFIED:
			/* Work-around for a bug in Lamp.mcc */
			if (gui_onlinestate < CONNECTING) set(gui->lamp, MUIA_Lamp_Color, MUIV_Lamp_Color_Off);
			else if (gui_onlinestate == ONLINE) set(gui->lamp, MUIA_Lamp_Color, MUIV_Lamp_Color_Ok);
			else set(gui->lamp, MUIA_Lamp_Color, MUIV_Lamp_Color_Connecting);
			break;
	}
	return(0);
}


void gui_state(enum OnlineState s)
{
	struct DateStamp ds;
	struct DateStamp *rds;
	u_long tmp;
	static char title[128], buf[128];

	gui_onlinestate = s;

	switch (s) {
		case DISCONNECTED:
			prf_event(PRFE_DISCONNECT);
			DoMethod(gui->WI_Hotlist, HOTLIST_SIGNOFF_ALL);
			gui->OnlineSince = 0;
			gui->Libraries = 0;
			gui->Songs     = 0;
			gui->Gigabytes = 0;
			nap_server[0] = '\0';
			nap_port   = 0;
		case OFFLINE:	/* Offline */
			set(gui->inbut, MUIA_Disabled, FALSE);
			set(gui->outbut, MUIA_Disabled, TRUE);
			set(gui->rebut, MUIA_Disabled, TRUE);

			sprintf(title, "Amster v%s · %s", AMSTER_VERSION, MSG_MAIN_TITLE_NOTCONNECTED);
			set(gui->win, MUIA_Window_Title, title);

			/* Work-around for a bug in Lamp.mcc */
			get(gui->app, MUIA_Application_Iconified, &tmp);
			if (!tmp) set(gui->lamp, MUIA_Lamp_Color, MUIV_Lamp_Color_Off);

			DoMethod(gui->searchpanel, SEARCH_CLEAR, CLEAR_ALL);
			DoMethod(gui->WI_Hotlist, HOTLIST_CLEAR, CLEAR_ALL);
			gui_appicon(2);
			break;
		case CONNECTING:	/* Connecting */
			set(gui->inbut, MUIA_Disabled, TRUE);
			set(gui->outbut, MUIA_Disabled, FALSE);

			sprintf(title, "Amster v%s · %s", AMSTER_VERSION, MSG_MAIN_TITLE_NOTCONNECTED);
			set(gui->win, MUIA_Window_Title, title);

			/* Work-around for a bug in Lamp.mcc */
			get(gui->app, MUIA_Application_Iconified, &tmp);
			if (!tmp) set(gui->lamp, MUIA_Lamp_Color, MUIV_Lamp_Color_Connecting);

			set(gui->stat, MUIA_Text_Contents, MSG_STATUS2_CONNECTING);
			break;
		case LOGGING_IN:	/* Logging in */
			prf_event(PRFE_CONNECT, nap_server, (int)nap_port);
			set(gui->inbut, MUIA_Disabled, TRUE);
			set(gui->outbut, MUIA_Disabled, FALSE);
			set(gui->rebut, MUIA_Disabled, FALSE);

			rds = DateStamp(&ds);
			sprintf(buf, "Amster v%s · %s", AMSTER_VERSION, MSG_MAIN_TITLE_CONNECTEDSINCE);
			sprintf(title, buf, nap_server, nap_port, rds->ds_Minute/60, rds->ds_Minute%60, rds->ds_Tick/50);
			set(gui->win, MUIA_Window_Title, title);
			gui->OnlineSince = rds->ds_Days*24*60*60 + rds->ds_Minute*60 + rds->ds_Tick/TICKS_PER_SECOND;

			/* Work-around for a bug in Lamp.mcc */
			get(gui->app, MUIA_Application_Iconified, &tmp);
			if (!tmp) set(gui->lamp, MUIA_Lamp_Color, MUIV_Lamp_Color_SendingData);

			break;
		case ONLINE:	/* Online */
			set(gui->inbut,  MUIA_Disabled, TRUE);
			set(gui->outbut, MUIA_Disabled, FALSE);
			set(gui->rebut,  MUIA_Disabled, FALSE);

			/* Work-around for a bug in Lamp.mcc */
			get(gui->app, MUIA_Application_Iconified, &tmp);
			if (!tmp) set(gui->lamp, MUIA_Lamp_Color, MUIV_Lamp_Color_Ok);

			gui_appicon(1);
			break;
	}
}


void gui_srvstat(int Libraries, int Songs, int Gigabytes)
{
	gui_stat((char *)MSG_STATUS2_SONGSONLINE, Songs, Libraries, Gigabytes);

	gui->Songs     = Songs;
	gui->Libraries = Libraries;
	gui->Gigabytes = Gigabytes;
}


void gui_found(song s, int type)
{
	if (type == 0) DoMethod(gui->searchpanel, SEARCH_FOUND, s);
	else if (type == 1) DoMethod(gui->WI_Hotlist, HOTLIST_FOUND, s);
}


void localize_array(char *array[])
{
	char **x;

	for (x=array;*x;x++)
		*x = (char *)((struct FC_String *)(*x))->msg;
}


void gui_stat(char *msg, ...)
{
	static char buf[256];
	struct Hook hook;
#ifdef __PPC__
	va_list ap;
	ULONG arg[32];
	int args = 0, i;

	for (i=0; msg[i] != '\0'; i++) {
		if (msg[i] == '%' && msg[i+1] != '%') args++;
	}

	va_start(ap, msg);
	for (i=0; i<args; i++) {
		arg[i] = va_arg(ap, ULONG);
	}
	va_end(ap);
#endif

	InitHook(&hook, putChar, buf);

#ifdef __PPC__
	FormatString(locale, msg, &arg[0], &hook);
#else
	FormatString(locale, msg, &msg+1, &hook);
#endif

/*
	va_start(ap,msg);
	vsprintf(buf,msg,ap);
	va_end(ap);
*/


/*
	RawDoFmt(msg, &ap, RAWDOFMT_COPY, &buf);
*/

	set(gui->stat, MUIA_Text_Contents, buf);
}


void gui_appicon(int t)
{
	static struct DiskObject *on, *off;

	switch(t) {
		case 0:
			on = GetDiskObject("PROGDIR:Icons/Amster_online");
			off = GetDiskObject("PROGDIR:Icons/Amster_offline");
			break;

		case -1:
			if (on) FreeDiskObject(on);
			if (off) FreeDiskObject(off);
			break;

		case 1:
			if (on) set(gui->app, MUIA_Application_DiskObject, on);
			break;

		case 2:
			if (off) set(gui->app, MUIA_Application_DiskObject, off);
			break;

	}
}
