/*
 ============================================================================
 Name        : ProjectParser.c
 Author      : Michael Lux
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <sys/fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "jsmn.c"
#include "jsmn.h"

int main(void) {

	int fd;
	char *myfifo = "/dev/rtf/0";

	mkfifo(myfifo, 0666);

	fd = open(myfifo, O_WRONLY);
	//set URL strings
	char *redURL = "https://smarthomeapi.herokuapp.com/data/get?address=1&category=klight";
	char *yellowURL = "https://smarthomeapi.herokuapp.com/data/get?address=1&category=blight";
	char *greenURL = "https://smarthomeapi.herokuapp.com/data/get?address=1&category=llight";

	jsmn_parser parser;
	int count = 0;
	int i;


	while(1){
		count += 12;
		jsmntok_t t[count];

		for(i = 0; i < count; i++){
			t[i].type = -1;
		}

		jsmn_init(&parser);
		//check and set red
		if(jsmn_parse(&parser, redURL, sizeof(t), t, count) == JSMN_ERROR_NOMEM)
			continue;
		i = 0;
		jsmntok_t t2 = t[7];
		if(t2.type == JSMN_STRING){
			char ss[sizeof(t2)];
			int i;
			for(i = t2.start; i < t2.end; i++){
				ss[i-t2.start] = redURL[i];
			}
			ss[i-t2.start] = '\0';

			if(!strcmp(ss, "True")){
				write(fd, "0", sizeof("0"));
			}else{
				write(fd, "1", sizeof("1"));
			}
		}
		//check and set yellow
		if(jsmn_parse(&parser, yellowURL, sizeof(t), t, count) == JSMN_ERROR_NOMEM)
			continue;
		i = 0;
		t2 = t[7];
		if(t2.type == JSMN_STRING){
			int i;
			char ss[sizeof(t2)];
			for(i = t2.start; i < t2.end; i++){
				ss[i-t2.start] = yellowURL[i];
			}
			ss[i-t2.start] = '\0';

			if(!strcmp(ss, "True")){
				write(fd, "2", sizeof("2"));
			}else{
				write(fd, "3", sizeof("3"));
			}
		}
		//check and set green
		if(jsmn_parse(&parser, greenURL, sizeof(t), t, count) == JSMN_ERROR_NOMEM)
			continue;
		i = 0;
		t2 = t[7];
		if(t2.type == JSMN_STRING){
			int i;
			char ss[sizeof(t2)];
			for(i = t2.start; i < t2.end; i++){
				ss[i-t2.start] = greenURL[i];
			}
			ss[i-t2.start] = '\0';
			if(!strcmp(ss, "True")){
				write(fd, "4", sizeof("4"));
			}else{
				write(fd, "5", sizeof("5"));
			}
		}
	}
	close(fd);
	unlink(myfifo);

	return EXIT_SUCCESS;
}

