#include "headers.h"

void client(int fd, int sem_id){
  /* Client code */
  time_t curr_t;
  time_t alarm_t;
  time_t this;
  time_t ring_t;
  char inbuff[MY_MAX];
  char alarmmesg[MY_MAX];
  char blah;
  char tempbuff[MY_MAX];
  int out_size;
  char *outbuf = "";
  const char *fifopath = "/tmp/alarm_fifo";
  struct tm *tmstr;
  /* Struct for waiting on the semaphore */
  static struct sembuf sem_wait[] = { 0, -1, 0 };
  /* Struct for signalling on the semaphore */
  static struct sembuf sem_signal[] = { 0, +1, 0 };
  
  printf("Enter the time in the following format:\n");
  printf("One o'clock in the afternoon would be 13:00:00.\n");
  printf("You may specify the day, month, and year like this:\n");
  printf("November 21, 1999 at 2:30 PM would be: 14:30:00 11/21/1999.\n");
  printf("If no day is specified, the current day is assumed.\n");
  printf("\nAt what time shall I ring: ");
  scanf("%s", &inbuff);
  /* Allows user to enter a string with spaces.  Very useful... */
  scanf("%c", &blah);
  if(blah != '\n'){
    scanf("%s", &tempbuff);
    strcat(inbuff, " ");
    strcat(inbuff, tempbuff);
  }
  printf("\nAnd what is the message to display: ");
  scanf("%s", &alarmmesg);
  while(1 != 2){
    scanf("%c", &blah);
    if(blah == '\n') break;
    else{
      scanf("%s", &tempbuff);
      strcat(alarmmesg, " ");
      strcat(alarmmesg, tempbuff);
    }
  }
  
  curr_t = time(&this);
  tmstr = localtime(&this);
  parser(inbuff, tmstr);
  alarm_t = mktime(tmstr);
  ring_t = alarm_t - curr_t;
  
  /* Talk to the dameon through the FIFO */
  out_size = strlen(alarmmesg);
  alarmmesg[out_size] = '\0';
  out_size++;
  write(fd, &out_size, sizeof(out_size));
  write(fd, alarmmesg, out_size);
  write(fd, &ring_t, sizeof(ring_t));
  close(fd);
  /* Now release the semaphore */
  if(semop(sem_id, sem_signal, 1) < 0){
    fprintf(stderr, "%s: semop() in parent\n", strerror(errno));
    abort();
  }
}