
#include <stdio.h>
#include <mxml.h>

#include "client_api.h"

void receive_events(char *_data)
{
	if( _data[6] == '1' )
	{   
		printf("%s\n", http_put_function ("http://localhost:8888/phidget/173111/output/1", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><value>1</value>\0"));
	}  

	else if( _data[6] == '0' )
		printf("%s\n", http_put_function ("http://localhost:8888/phidget/173111/output/1", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><value>0</value>\0"));
		
	
	
}

char* get_value_from_xml_value2(char* _xml_value)
{
    mxml_node_t *xml;
    mxml_node_t *node;

    xml = mxmlLoadString(NULL, _xml_value, MXML_TEXT_CALLBACK);
    node = mxmlFindElement(xml, xml, "subscription", NULL, NULL, MXML_DESCEND);

    char *return_value = malloc(sizeof(char)*(strlen(node->child->value.text.string)+1));
    strcpy(return_value, node->child->value.text.string);

    mxmlDelete(xml);
	
    return return_value;
}


int main()
{

	pthread_t events_thread;

	char *tmp=NULL;

	init_curl (receive_events);

	while( 1 )
	{
		tmp = get_value_from_xml_value2 (http_get_function ("http://localhost:8888/phidget/173111/input/1?p=1"));

		if ( strcmp( tmp, "yes" ) == 0 )
		{
			free(tmp);
			break;
		}
		free(tmp);                                                   
	}
	
	getchar();

	pthread_create(&events_thread, NULL, http_get_events_function, "http://localhost:8888/events");

	getchar();

	while( 1 )
	{
		tmp = get_value_from_xml_value2 (http_get_function ("http://localhost:8888/phidget/173111/input/0?p=1"));

		if ( strcmp( tmp, "yes" ) == 0 )
		{
			free(tmp);
			break;
		}
		free(tmp);                                                   
	}

	getchar();
	               
	deinit_curl();

	pthread_join( events_thread, NULL );
	
	return 0;
}
