#include <stdio.h>
#include <unistd.h>
#include "commondef.h"
#include "hub.h"


#include "commondef.h"

typedef struct
{
    int temperature;
    int pressure;
    int light;

    Doorstatus door;
    Motionstatus motion;
    Fanstatus fan;

    pthread_mutex_t lock;

} HomeData;

static HomeData g_homeData;



void home_data_init(void)
{
    pthread_mutex_init(&g_homeData.lock, NULL);

}

void home_data_destroy(void)
{
    pthread_mutex_destroy(&g_homeData.lock);
    printf("\nHome Automation System Stopped.\n");
}


void set_temperature(int temp)
{
    pthread_mutex_lock(&g_homeData.lock);
    g_homeData.temperature = temp;
    pthread_mutex_unlock(&g_homeData.lock);
}

int get_temperature(void)
{

    return g_homeData.temperature;
}



void set_pressure(int pressure)
{
    pthread_mutex_lock(&g_homeData.lock);
   g_homeData.pressure = pressure;
    pthread_mutex_unlock(&g_homeData.lock);
}

int get_pressure(void){
    return g_homeData.pressure;
}



void set_light(int light)
{
    pthread_mutex_lock(&g_homeData.lock);
    g_homeData.light = light;
    pthread_mutex_unlock(&g_homeData.lock);
}

int get_light(void)
{


    return g_homeData.light;
}

void set_door(Doorstatus status)
{
    pthread_mutex_lock(&g_homeData.lock);
    g_homeData.door = status;
    pthread_mutex_unlock(&g_homeData.lock);
}

Doorstatus get_door(void)
{

    
    return g_homeData.door;
}



void set_motion(Motionstatus status)
{
    pthread_mutex_lock(&g_homeData.lock);
    g_homeData.motion = status;
    pthread_mutex_unlock(&g_homeData.lock);
}

Motionstatus get_motion(void)
{


    return g_homeData.motion;;
}

/* Fan */

void set_fan(Fanstatus status)
{
    pthread_mutex_lock(&g_homeData.lock);
    g_homeData.fan = status;
    pthread_mutex_unlock(&g_homeData.lock);
}

Fanstatus get_fan(void)
{
    

    return g_homeData.fan;
}






void *hub_controller_thread(void *arg)
{
    int i=0;
	while (1)
	{
        
		pthread_mutex_lock(&g_homeData.lock);

		printf("\n");
		printf("Hub Status\n");
		printf("-----------------------------\n");

		printf("Temperature : %d C\n",
			   get_temperature());

		printf("Pressure    : %d hPa\n",
			   get_pressure());

		printf("Door Status : %s\n",
			   get_door() == DOOR_OPEN
				   ? "OPEN"
				   : "CLOSED");

		printf("Motion      : %s\n",
			   get_motion() == MOTION_DETECTED
				   ? "DETECTED"
				   : "NO MOTION");

		printf("Light Level : %d Lux\n",
			   get_light());

		printf("Fan Status  : %s\n",
			   get_fan() == FAN_ON
				   ? "ON"
				   : "OFF");

		printf("-----------------------------\n");
		printf("-----------------------------\n");
        

		pthread_mutex_unlock(&g_homeData.lock);
        i++;
        

		sleep(1);
        if (i==10)
        {
            return NULL;
        }
	}

	return NULL;
}