#ifndef __COMMON_H__
#include "common.h"
#endif /* __COMMON_H__ */

extern struct PopData *pd;

struct Library *CxBase;

/*
 * ho hum..the lowly life of a commodity
 * maybe we should commit Cxcide
 */
VOID disposeCx(VOID)
{
   if(pd->pd_cxBroker)
   {
      DeleteCxObjAll(pd->pd_cxBroker);
      pd->pd_cxBroker = NULL;
   }
   if(CxBase)
   {
      CloseLibrary((struct Library*)CxBase);
   }
}

/*
 * Molson Ice...but uhm..beware the penguin
 */
BOOL createCx(struct MsgPort *port)
{
   struct NewBroker nb;
   CxObj *filter;

   disposeCx();

   if(!(CxBase = (struct Library*)OpenLibrary("commodities.library", 40)))
   {
      return(FALSE);
   }

   nb.nb_Version         = NB_VERSION;
   nb.nb_Name            = "IPop";
   nb.nb_Title           = VERS;
   nb.nb_Descr           = "AppIcon POP Checker";
   nb.nb_Unique          = NBU_NOTIFY | NBU_UNIQUE;
   nb.nb_Pri             = pd->pd_cxPriority;
   nb.nb_Port            = port;
   nb.nb_ReservedChannel = NULL;
   nb.nb_Flags           = COF_SHOW_HIDE;

   if(pd->pd_cxBroker = CxBroker(&nb, NULL))
   {
      /* install a hotkey for popping up window   */
      filter = CxFilter(pd->pd_cxPopKey);
      AttachCxObj(filter, CxSender(port, 86));
      AttachCxObj(filter, CxTranslate(NULL));
      AttachCxObj(pd->pd_cxBroker, filter);

      if(CxObjError(pd->pd_cxBroker) == 0)
      {
         ActivateCxObj(pd->pd_cxBroker, 1);
         return(TRUE);
      }
      DeleteCxObjAll(pd->pd_cxBroker);
   }
   return(FALSE);
}

/*
 * handle the commodity
 */
BOOL processCxMsg(CxMsg *msg)
{
   ULONG msgID;
   ULONG msgType;

   msgID   = CxMsgID(msg);
   msgType = CxMsgType(msg);
   ReplyMsg((struct Message *)msg);

   switch(msgType)
   {
      case CXM_IEVENT:
      {
         switch(msgID)
         {
            case 86:
            {
               openHWindow(pd);
               break;
            }
         }
         break;
      }

      case CXM_COMMAND:
      {
         switch(msgID)
         {
            case CXCMD_DISABLE:  /* disable ourselves */
            {
               ActivateCxObj(pd->pd_cxBroker, 0);
               break;
            }

            case CXCMD_ENABLE:   /* enable ourselves */
            {
               ActivateCxObj(pd->pd_cxBroker, 1);
               break;
            }

            case CXCMD_APPEAR:
            case CXCMD_UNIQUE:
            {
               openHWindow(pd);
               break;
            }

            case CXCMD_DISAPPEAR:
            {
               closeHWindow(pd);
               break;
            }

            case CXCMD_KILL:     /* mama tryme */
            {
               return(FALSE);
            }
         }
      }
   }
   return(TRUE);
}
