#include "archinc.h"
#include "board.h"
#include "cli.h"
#include "clichar.h"
#include "eventq.h"
#include "events.h"

#include <stdio.h>

static int iostatHandler(int argc, char * argv[], int flags);
static int greenLedHandler(int argc, char * argv[], int flags);

#ifdef CONFIG_TOOLCHAIN_IAR
//#pragma inline
#endif
void INLINE_KEYWORD boardSetBusyLed(boolean onOff)
{
#ifdef CONFIG_BOARD_MEDUSA
  medusaSetOrangeLed(onOff);
#endif
}

#ifdef CONFIG_TOOLCHAIN_IAR
#pragma inline
#endif
void INLINE_KEYWORD boardSetTimerLed(boolean onOff)
{
#ifdef CONFIG_BOARD_MEDUSA
  medusaSetGreenLed(onOff);
#endif

#ifdef CONFIG_BOARD_OLIMEX
  if (onOff == false)
    olimexLedOff();
  else
    olimexLedOn();
#endif
}

#ifdef CONFIG_TOOLCHAIN_IAR
//#pragma inline
#endif
void INLINE_KEYWORD boardTimerLedToggle(void)
{
#ifdef CONFIG_BOARD_MEDUSA
  medusaToggleGreenLed();
#endif
#ifdef CONFIG_BOARD_OLIMEX
  olimexLedToggle();
#endif
}

static void handleRunLedOnEvent(void)
{
  boardSetTimerLed(true);
}

static void handleRunLedOffEvent(void)
{
  boardSetTimerLed(false);
}

void boardInit(void)
{
#ifdef CONFIG_BOARD_OLIMEX
  olimexInit();
#endif

#ifdef CONFIG_BOARD_MEDUSA
  medusaInit();
#endif
}

void boardInit2(void)
{
  // connect us to the console
  eventqRegisterHandler(RUN_LED_ON,  handleRunLedOnEvent );
  eventqRegisterHandler(RUN_LED_OFF, handleRunLedOffEvent);

  cliRegisterCommand("iostat", iostatHandler, "iostat - shows lpc210x IOPIN and IODIR regs");
  cliRegisterCommand("runled", greenLedHandler, "runled - turn on and off the run LED");
}

static int iostatHandler(int argc, char * argv[], int flags)
{
  int retVal = -1;
  int bufLen;
  char * pOutBuf;

  pOutBuf = clicharGetOutputBuffer(&bufLen);
  
  // TODO: put this in a while loop to process a list of op/data pairs

  sprintf(pOutBuf, "IOPIN[%08x] IODIR[%08x]\n", ((IOPIN) & 0xffffffff), ((IODIR) & 0xffffffff) );
  clicharSendOutputBuffer(pOutBuf, bufLen);
  retVal = 0;

  return retVal;
}

static int greenLedHandler(int argc, char * argv[], int flags)
{
  int retVal = -1;
  int bufLen;
  char * pOutBuf;

  if (argc != 2)
    return -1;

  switch(*argv[1]) {
    case 'n':
    case 'N':
    case '0':
      boardSetTimerLed(false);
      retVal = 0;
      break;
    case 'y':
    case 'Y':
    case '1':
      boardSetTimerLed(true);
      retVal = 0;
      break;
    }

  return retVal;
}
  
