/*
** OpenURL - MUI preferences for openurl.library
** Written by Troels Walsted Hansen <troels@thule.no>
** Placed in the public domain.
**
** This module contains the code to the App Application.mui subclass.
*/

#include "prefs_common.h"
#include "prefs_main.h"
#include "prefs_app.h"

/**************************************************************************/

static ULONG mOpenWin (struct IClass *cl, Object *obj, struct MUIP_App_OpenWin *msg);
static ULONG mCloseWin(struct IClass *cl, Object *obj, struct MUIP_App_CloseWin *msg);

static Object *FindWinObjByAttr(Object *app, ULONG attr, ULONG val);

/**************************************************************************/

static ULONG mOpenWin(struct IClass *cl, Object *obj, struct MUIP_App_OpenWin *msg)
{
	Object *win = FindWinObjByAttr(obj, msg->IDAttr, msg->IDVal);

	if(!win)
	{
		win = NewObject(msg->Class, NULL, 
		                msg->IDAttr, msg->IDVal,
		                TAG_MORE, &msg->InitAttrs);

		if(win)
			DoMethod(obj, OM_ADDMEMBER, win);
		else 
		{
			DisplayBeep(NULL);
			return(FALSE);
		}
	}

	set(win, MUIA_Window_Open, TRUE);
	return((ULONG)xget(win, MUIA_Window_Open));
}

/**************************************************************************/

static ULONG mCloseWin(struct IClass *cl, Object *obj, struct MUIP_App_CloseWin *msg)
{
	Object *win = FindWinObjByAttr(obj, msg->IDAttr, msg->IDVal);

	if(win)
	{
		set(win, MUIA_Window_Open, FALSE);
		DoMethod(obj, OM_REMMEMBER, win);
		MUI_DisposeObject(win);
	}

	return(TRUE);
}

/**************************************************************************/

SAVEDS ASM ULONG App_Dispatcher(REG(a0) struct IClass *cl, REG(a2) Object *obj, REG(a1) Msg msg)
{
	switch(msg->MethodID)
	{
		case MUIM_App_OpenWin : return(mOpenWin (cl,obj,(APTR)msg));
		case MUIM_App_CloseWin: return(mCloseWin(cl,obj,(APTR)msg));
	}

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

/**************************************************************************/

static Object *FindWinObjByAttr(Object *app, ULONG attr, ULONG val)
{
	struct List *winlist;
	Object *obj;
	APTR state;

	/* return the window object which supports OM_GET on attr, and 
	   whose value of attr == val */

	get(app, MUIA_Application_WindowList, &winlist);
	state = winlist->lh_Head;

	while(obj = NextObject(&state))
	{
		ULONG value;
		if(get(obj, attr, &value) && (value == val)) break;
	}

	return(obj);
}
