/*
	Code to test AppWindow feature of Workbench.
*/

#include <intuition/intuition.h>
#include <workbench/startup.h>
#include "workbench/workbench.h"

#define INTUITIONNAME	"intuition.library"
#define WORKBENCHNAME	"workbench.library"

struct IntuitionBase *IntuitionBase = NULL;
struct WorkbenchBase *WorkbenchBase = NULL;

struct NewWindow nw = {
	0, 0,		/* leftedge, topedge */
	160,50,		/* width, height */
	-1, -1,		/* DetailPen, BlockPen */
	CLOSEWINDOW,		/* IDCMP flags */
	WINDOWCLOSE|WINDOWDRAG,		/* flags */
	NULL,		/* FirstGadget */
	NULL,		/* Image */
	"AppWindow",	/* Title */
	NULL,		/* Screen */
	NULL,		/* BitMap */
	0, 0,		/* MinWidth, MinHeight */
	0, 0,		/* MaxWidth, MaxHeight */
	WBENCHSCREEN	/* type */
};

main(argc, argv)
int argc;
char **argv;
{
	void *OpenLibrary();
	struct MsgPort *CreatePort();
	struct Window *OpenWindow();
	struct IntuiMessage *GetMsg();
	struct AppWindow *AddAppWindow();

	struct MsgPort *msgport = NULL;
	struct Window *win = NULL;
	struct AppWindow *aw = NULL;
	struct IntuiMessage *imsg;
	struct AppMessage *amsg;
	struct WBArg *argptr;
	ULONG userdata = 0;
	ULONG id = 1;
	BOOL done = FALSE;
	int i;

	printf("aw: enter\n");
	if (!(IntuitionBase = OpenLibrary(INTUITIONNAME, 0))) {
		printf("aw: could not open intuition\n");
		goto err;
	}
	if (!(WorkbenchBase = OpenLibrary(WORKBENCHNAME, 36))) {
		printf("aw: could not open workbench\n");
		goto err;
	}
	if (!(msgport = CreatePort("appwindow", 0))) {
		printf("aw: could not createport\n");
		goto err;
	}
	if (!(win = OpenWindow(&nw))) {
		printf("aw: could not openwindow\n");
		goto err;
	}
	printf("aw: calling AddAppWindow...", win);
	if (!(aw = AddAppWindow(id, userdata, win, msgport))) {
		printf("aw: could not addappwindow\n");
		goto err;
	}
	printf("aw: ok, aw = %lx, going to sleep\n", aw);
	do {
		Wait((1 << win->UserPort->mp_SigBit) |
			(1 << msgport->mp_SigBit));
		while (imsg = GetMsg(win->UserPort)) {
			if (imsg->Class == CLOSEWINDOW) {
				done = TRUE;
			}
		};
		while (amsg = GetMsg(msgport)) {
			printf("aw: appmsg=%lx, Type=%ld, ID=%ld, UserData=%ld, NumArgs=%ld\n", amsg, amsg->am_Type, amsg->am_ID, amsg->am_UserData, amsg->am_NumArgs);
			argptr = amsg->am_ArgList;
			for (i=0; i<amsg->am_NumArgs; i++) {
				printf("\targ(%ld): Name='%s', Lock=%lx\n",
				i, argptr->wa_Name, argptr->wa_Lock);
				argptr++;
			}
			ReplyMsg(amsg);
		};
	} while (!done);

	if (aw) {
		printf("aw: calling RemoveAppWindow\n");
		RemoveAppWindow(aw);
	}

err:
	if (win) {
		CloseWindow(win);
	}
	if (msgport) {
		DeletePort(msgport);
	}
	if (WorkbenchBase) {
		CloseLibrary(WorkbenchBase);
	}
	if (IntuitionBase) {
		CloseLibrary(IntuitionBase);
	}
	printf("aw: exit\n");
}
