/* riscnet.c
 *
 * POPstar: Acorn POP3 client / SMTP send
 * RiscNet interface code
 *
 *  Joseph Heenan, 1998
 *
 * This file contains all code to support RiscNet's various
 * wimp messages to control POPstar.
 *
 * $Id: riscnet,v 1.2 1999/10/05 22:33:51 joseph Exp $
 *
 */

#include <stdlib.h>
#include "swis.h"
#include "wimplib.h"
#include "log.h"
#include "stopquit.h"
#include "popstar.h"

#include "riscnet.h"

int riscnet_present = 0;

static int riscnet_taskhan = -1;

/* riscnet_init
 *
 * checks to see if riscnet module is present, and sets riscnet_present if it is
 */
void riscnet_init( void )
{
  if ( _swix( OS_Module, _INR(0,1), 18, "Riscnet" ) )
    /* error -> module not present */
    riscnet_present = 0;
  else
    /* module is present */
    riscnet_present = 1;

  xsyslogf( log_NAME, log_DebugInfo, "riscnet_init: riscnet_present = %d", riscnet_present );
}

void riscnet_mailfinish( int newmsgs )
{
  WimpMessage msg;

  if ( riscnet_taskhan == -1 )
  {
    xsyslogf( log_NAME, log_DebugInfo, "riscnet_mailfinish: newmsgs = %d, but riscnet not present", newmsgs );
    return; /* don't know riscnet's taskhan */
  }

  msg.hdr.size        = sizeof(msg.hdr) + sizeof(int);
  /*  msg.hdr.sender  = wimp fills in */
  /*  msg.hdr.my_ref  = wimp fills in */
  msg.hdr.your_ref    = 0;
  msg.hdr.action_code = Riscnet_Mail_Finish;
  msg.data.words[0]   = newmsgs;

  wimp_send_message( Wimp_EUserMessage, &msg, riscnet_taskhan, 0 /*NU icon*/, NULL /*NU dest task han*/ );

  xsyslogf( log_NAME, log_DebugInfo, "riscnet_mailfinish: sent message, newmsgs = %d to taskhan %d",
            newmsgs, riscnet_taskhan );
}

static void riscnet_ackmsg( WimpMessage *msg )
{
  riscnet_taskhan = msg->hdr.sender; /* store riscnet's task handle */

  msg->hdr.your_ref = msg->hdr.my_ref;
  wimp_send_message( Wimp_EUserMessageAcknowledge, msg, msg->hdr.sender, 0, NULL );
}

void riscnet_wimpmessage( WimpMessage *msg )
{
  /* NB. Handled messages must be added to wimp_messages in popstar.c as well as here */
  switch ( msg->hdr.action_code )
  {
    case Riscnet_Mail_RequestFetch:
      riscnet_ackmsg( msg );
      xsyslogf( log_NAME, log_DebugInfo, "riscnet_mail_requestfetch received" );
      popstar_fetchallhandler();
      break;

    case Riscnet_Mail_SendNew:
      riscnet_ackmsg( msg );
      xsyslogf( log_NAME, log_DebugInfo, "riscnet_mail_sendnew received" );
      popstar_sendhandler();
      break;

    case Riscnet_Offline:
      xsyslogf( log_NAME, log_DebugInfo, "Riscnet_Offline received" );
      stopquit_handler( stopquit_Quit ); /* quit popstar, closing down current fetch/send if needed */
      break;

    default:
      /* unrecognised message, ignore it */
      break;
  }
}
