/**Chris Jarrett
 * Comp289 - Lab7
 * Usage: MsgSender <logger executable>
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/neutrino.h>
#include <string.h>
#include "msg.h"

void createMessage(MESSAGE_CLIENT *message, MSG_TYPE messageBody[MSG_SIZE], int *type);
void setupPulseAndTimer(int coid);

int main(int argc, char *argv[]) {
	char *loggerPidName;
	FILE *pidFile;
	int nd, pid, chid, coid, status;
	MSG_HEADER type;
	MSG_TYPE messageBody[MSG_SIZE];;
	MESSAGE message;

	//not the right number of args
	if(argc != 2) {
		printf("Incorrect arguments. Should be: \"%s <logger>\".", argv[0]);
		return EXIT_FAILURE;
	}

	//get pid file to read from input
	loggerPidName = malloc(strlen(argv[1]) + 5);
	strcpy(loggerPidName, argv[1]);
	strcat(loggerPidName, ".pid");

	//open the pid file
	pidFile = fopen(loggerPidName, "r");

	//error opening
	if(pidFile == NULL) {
		printf("I Could not find pid file %s", loggerPidName);
		return EXIT_FAILURE;
	}

	//read the pid, open the connection, and close file
	fscanf(pidFile, "%d %d %d", &nd, &pid, &chid);
	coid = ConnectAttach(nd, pid, chid, 1, NULL);
	fclose(pidFile);

	//if conenction doesn't open
	if(coid == -1) {
		printf("Could not connect to logger\n");
		return EXIT_FAILURE;
	}

	//start the pulse timer
	setupPulseAndTimer(coid);

	while(1) {
		//get the messagee type
		printf("Enter the message type (max 3 digits): ");
		fflush(stdout);
		scanf("%d", &type);

		//if it's a non-set type
		if(type != MSG_DATA && type != MSG_END) {
			printf("Enter a valid message type(Data=1, End=31)\n");
			continue;
		}

		//get the message data
		printf("Enter the message:\n");
		scanf("%s", messageBody);

		//if larger than maximum message size
		if(strlen(messageBody) > MSG_SIZE) {
			printf("Message too large, maximum size is %d\n", MSG_SIZE);
			continue;
		}

		//create and send message
		createMessage(&message.client, messageBody, &type);
		status = MsgSend(coid, &message, sizeof(message), NULL, 0);

		//handle the reply cases
		switch(status) {
			case MSG_OK:
				printf("Message successfully received\n");
				break;
			case MSG_INVALID:
				printf("Invalid message\n");
				break;
			case MSG_END:
				printf("Server says goodbye\n");
				return EXIT_SUCCESS;
			default:
				printf("Server error: Bad file descriptor\n");
				return EXIT_FAILURE;
		}
	}
}

/**
 * function to create a message
 */
void createMessage(MESSAGE_CLIENT *message, MSG_TYPE messageBody[MSG_SIZE], int *type) {
	//copy the data
	strcpy(message->m_data, messageBody);
	//set the header type
	message->m_hdr = *type;
	return;
}

/**
 * function to make and initialize the pulse timer
 *
 * maybe should be done in logger, but the instructions
 * aren't clear and I see it being used later as a keep-alive method
 */
void setupPulseAndTimer(int coid) {
	timer_t timerid; // timer ID for timer
	struct sigevent event; // event to deliver
	struct itimerspec timer; // the timer data struct


	// set up the event that we want to deliver -- a pulse
	SIGEV_PULSE_INIT (&event, coid, SIGEV_PULSE_PRIO_INHERIT, MSG_PULSE_ALIVE, 0);
	// create the timer, binding it to the event
	if(timer_create(CLOCK_REALTIME, &event, &timerid) == -1) {
		fprintf (stderr, "couldn't create a timer");
		perror (NULL);
		exit (EXIT_FAILURE);
	}
	// setup the timer (1s delay, 1s reload)
	timer.it_value.tv_sec = 3;
	timer.it_value.tv_nsec = 0;
	timer.it_interval.tv_sec = 5;
	timer.it_interval.tv_nsec = 0;
	// and start it!
	timer_settime (timerid, 0, &timer, NULL);
}

