/* Test creating and destroying message queues.
 * Create a message queue and a reader thread.
 * Write messages to queue.
 * Verify that reader thread can read the messages.
 */

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>

#define STACK_SIZE 1024
const u8 _initStack[STACK_SIZE*2];
const u32 _initStackSize = sizeof(_initStack);
const u32 _initPriority = 10;
#define IOS_ThreadExit exit

#define ITER_LIMIT 10

IOSMessageQueueId qid = -1;
IOSMessage msgQ[4];

int ctr = 0;
char progStack[STACK_SIZE];
/* Create a thread of higher priority than current thread.
 * It creates a msgQ and puts id in global, lowers it priority/
 * Send msg to thread. Thread reads message.
 */


static void
rdr_thread(u32 x)
{
  char *msg;
  qid = IOS_CreateMessageQueue(msgQ, 4);
  if ( qid < 0 ) {
    printf("creating msg queue failed: %d", qid);
    exit(0);
  }
  while (1) {
      printf("Reader blocking to receive message\n");
      IOS_ReceiveMessage(qid, (IOSMessage *) &msg, IOS_MESSAGE_BLOCK);
      if ( NULL == msg) {
          printf("Received null message\n");
	  break;
      }
      printf("reader read msg: %s\n", msg);
  }
    IOS_DestroyMessageQueue(qid);
  IOS_DestroyThread(0, NULL);
}

static void 
create_rdr()
{
    u32 id = IOS_CreateThread(rdr_thread, 0, progStack+STACK_SIZE, STACK_SIZE, IOS_GetThreadPriority(0), IOS_THREAD_CREATE_DETACHED);
    IOS_StartThread(id);
}

static void
send_msgs()
{
    IOSError err;
    char msg[] = "tst-msg";
    while(ctr < ITER_LIMIT) {
        if ( -1 == qid) 
            IOS_YieldThread(); 
        printf("writer sending msg: %s\n", msg);
        err = IOS_SendMessage(qid, (IOSMessage) msg, IOS_MESSAGE_BLOCK);
        if ( err != IOS_ERROR_OK ) {
            printf("SendMessage failed: %d", err);
            exit(0);
        }
	ctr ++;
    }
    IOS_SendMessage(qid, NULL, IOS_MESSAGE_BLOCK);
}

static void 
test_sndmsg()
{
    create_rdr();
    send_msgs();
}

void
msg(u32 id)
{
  test_sndmsg();
  IOS_DestroyThread(0, NULL);
}


void
main(u32 arg)
{
  ctr = 0;
  msg(arg);
}
