/*
** OpenURL - MUI preferences for openurl.library
** Written by Troels Walsted Hansen <troels@stud.cs.uit.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"
#include "prefs_editwin.h"

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

static ULONG mOpenEditWin (struct IClass *cl, Object *obj, struct MUIP_App_OpenEditWin *msg);
static ULONG mCloseEditWin(struct IClass *cl, Object *obj, struct MUIP_App_CloseEditWin *msg);

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

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

static ULONG mOpenEditWin(struct IClass *cl, Object *obj, struct MUIP_App_OpenEditWin *msg)
{
	Object *win = FindWinObjByAttr(obj, MUIA_EditWin_Browser, msg->Browser);

	if(!win)
	{
		win = NewObject(EditWinClass->mcc_Class, NULL,
		                MUIA_EditWin_Browser, msg->Browser,
		                MUIA_EditWin_ListObj, msg->ListObj,
		                TAG_END);

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

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

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

static ULONG mCloseEditWin(struct IClass *cl, Object *obj, struct MUIP_App_CloseEditWin *msg)
{
	Object *win = FindWinObjByAttr(obj, MUIA_EditWin_Browser, msg->Browser);

	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_OpenEditWin : return(mOpenEditWin (cl,obj,(APTR)msg));
		case MUIM_App_CloseEditWin: return(mCloseEditWin(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);
}
