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

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

void createMessage(MESSAGE *message, MSG_TYPE messageBody[MSG_SIZE], int *type);

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;
	}

	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, 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 *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;
}

