#include <intuition/intuition.h>
#include <libraries/commodities.h>
#include "split.h"

#include <clib/alib_protos.h>
#include <proto/intuition.h>
#include <proto/commodities.h>
#include <proto/exec.h>

/* for debug purposes */
#include <stdio.h>

/* in split.c */
extern BOOL stay;

/* in window.c */
extern void openGUI( void );
extern void closeGUI( void );
extern void quit( void );
extern UWORD wleft, wtop;

/* end of external definitions */

struct NewBroker newbroker = {
	NB_VERSION,
	"Split",
	"Split v1.0 © 1995 by Stefano Reksten",
	NULL,
	NBU_UNIQUE | NBU_NOTIFY,
	COF_SHOW_HIDE, 0, 0, 0 };

struct Library *CxBase;

char *hotkey = "ctrl lalt f";

CxObj *broker, *keyfilter, *keysender, *keykiller;
struct MsgPort *mport;
ULONG brokerSig;


BOOL setUpCommodity( int argc, char **argv )
{
struct Library *IconBase;

if ( IconBase = OpenLibrary( "icon.library", 37L ) )
	{
	char **ttypes;

	ttypes = ArgArrayInit( argc, argv );
	newbroker.nb_Pri = ArgInt( ttypes, "CX_PRIORITY", 0 );
	hotkey = ArgString( ttypes, "CX_POPKEY", hotkey );
	wleft = ArgInt( ttypes, "WLEFT", ~0 );
	wtop = ArgInt( ttypes, "WTOP", ~0 );
	ArgArrayDone();
	CloseLibrary( IconBase );
	}

if ( CxBase = OpenLibrary( "commodities.library", 0L ) )
	{
	if ( mport = CreateMsgPort() )
		{
		newbroker.nb_Port = mport;

		if ( broker = CxBroker( &newbroker, NULL ) )
			{
			brokerSig = 1L<<mport->mp_SigBit;

			if ( keyfilter = CxFilter( hotkey ) )
				{
				AttachCxObj( broker, keyfilter );

				if ( keysender = CxSender( mport, EVT_POPKEY ) )
					{
					AttachCxObj( keyfilter, keysender );

					if ( keykiller = CxTranslate( NULL ) )
						{
						AttachCxObj( keyfilter, keykiller );

						if ( !( CxObjError( keyfilter ) ) )
							{
							ActivateCxObj( broker, 1L );
							return TRUE;
							}
						else
							{
							DeleteCxObjAll( broker );
							return FALSE;
							}
						}
					}
				}
			}
		}
	}
}


void removeCommodity( void )
{
CxMsg *cxm;

DeleteCxObjAll( broker );
while( cxm = (CxMsg *)GetMsg( mport ) )
	ReplyMsg( (struct Message *)cxm );
DeleteMsgPort( mport );
}


void handleBrokerSig( void )
{
CxMsg *msg;
ULONG msgid, msgtype;

while( stay && ( msg = (CxMsg *)GetMsg( mport ) ) )
	{
	msgid = CxMsgID( msg );
	msgtype = CxMsgType( msg );
	ReplyMsg( (struct Message *)msg );

	switch( msgtype )
		{
		case CXM_IEVENT:
			switch( msgid )
				{
				case EVT_POPKEY:
					openGUI();
					break;
				}
			break;
		case CXM_COMMAND:
			switch( msgid )
				{
				case CXCMD_DISABLE:
					ActivateCxObj( broker, 0L );
					break;
				case CXCMD_ENABLE:
					ActivateCxObj( broker, 1L );
					break;
				case CXCMD_KILL:
					quit();
					break;
				case CXCMD_UNIQUE:
				case CXCMD_APPEAR:
					openGUI();
					break;
				case CXCMD_DISAPPEAR:
					closeGUI();
					break;
				}
			break;
		}
	}
}
