#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <gtk/gtk.h>
#include <strings.h>

#include "msq.h"
#include "express.h"

#define MSQKEY 7365
#define MSQSIZE 256 

struct msq_buf {
  long mtype;
  BWindow *bwindow;
  char mtext[MSQSIZE];
};

int rcv_msqid;

int msq_snd_init(void)
{
  key_t key;
  int snd_msqid;
  
  key = MSQKEY;
  if((snd_msqid=msgget(key, 0666))<0) {
    perror("snd msgget");
    _exit(1);
  }
  return snd_msqid;
}

void msq_snd(int snd_msqid, BWindow *bwindow, char *mtext)
{
  struct msq_buf mb;

  g_print("In msq_snd()\n");

  mb.mtype=(long)MSQ_STATUS;
  mb.bwindow = bwindow;
  strncpy(mb.mtext, mtext, MSQSIZE);
  if(msgsnd(snd_msqid, (void *)&mb, strlen(mb.mtext) + sizeof(mb.bwindow), 0) < 0) {
    perror("msgsnd");
    _exit(1);
  }
  g_print("Out msq_snd()\n");
}

void msq_rcv_init(void)
{
  key_t key;

  key = MSQKEY;
  if((rcv_msqid=msgget(key, IPC_CREAT | IPC_EXCL | 0666)) < 0) {
    perror("rcv msgget");
    cleanexit(1);
  }
}

void msq_rcv_check(gpointer data)
{
  int n;
  struct msq_buf mb;

  if((n=msgrcv(rcv_msqid, (void *)&mb, MSQSIZE, 0, IPC_NOWAIT)) > 0) {
    switch(mb.mtype) {
      case MSQ_STATUS:
        mb.mtext[n-sizeof(mb.bwindow)] = '\0';
        bwindow_set_status(mb.bwindow, mb.mtext);
        break;
      default:
        break;
    }
  }
}

void msq_rm(void)
{
  if(msgctl(rcv_msqid, IPC_RMID, (struct msqid_ds *)0) < 0) {
    perror("msgctl");
    cleanexit(1);
  }
}
