/* jawsd - connects to AWS datalogger over serial connection and provides
 *         weather information to the network
 * Copyright (C) 2003-2004 Jeffrey Grafton <jgrafton@tjhsst.edu>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <curl/curl.h>
#include <pthread.h>
#include <syslog.h>

#include "config.h"
#include "data_types.h"
#include "wunderground.h"

MYSQL mysql;
int setup_mysql (void)
{
	mysql_init(&mysql); 
	if (!mysql_real_connect(&mysql, MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE, 0, NULL, 0))
	{
		return 1;
	}
	return 0;
}

int destroy_mysql (void)
{
	mysql_close(&mysql);
	return 0;
}


	void *
update_wunderground (void *voidptr)
{
	CURL *curl;
	CURLcode result;
	data_processed *processed = (data_processed *)voidptr;
	double last_rain = -1.0, rain, high_wind;
	struct tm utc,local_time;
	int last_day = 0;
	char url[512] = "";
	char query[512]="";
	FILE *logfile;

	syslog(LOG_INFO, "update_wunderground: running.");

	if (setuid(UID) == -1)
	{
		perror("setuid");
	}
	else
	{
		printf("update_wunderground dropped to uid %d\n", getuid());
	}

	sleep(5);

	logfile = fopen("weather.log", "a");

	curl = curl_easy_init();

	if (!curl)
		pthread_exit(0);

	while (1)
	{
		localtime_r(&processed->datetime, &local_time);
		gmtime_r(&processed->datetime, &utc);

		if (last_rain < 0)
			rain = 0;
		else if (last_day == utc.tm_mday)
			rain = processed->rain.daily - last_rain;
		else
			rain = processed->rain.daily;
		last_rain = processed->rain.daily;
		last_day = utc.tm_mday;

		if (processed->wind.current_speed > processed->wind.average_speed)
			high_wind = processed->wind.current_speed;
		else
			high_wind = processed->wind.average_speed;

		snprintf(url, 512, "%s?action=updateraw&ID=%s&PASSWORD=%s&dateutc=%04d-%02d-%02d+%02d:%02d:%02d&winddir=%g&windspeedmph=%g&windgustmph=%g&humidity=%g&tempf=%g&rainin=%g&baromin=%g&dewptf=%g&softwaretype=jgrafton_weather_techlab",
				"http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php",
				WUNDERSTATION, WUNDERPASS, utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec, processed->wind.average_direction_degrees, processed->wind.average_speed, high_wind, processed->humidity.current, processed->outdoor_temperature.current, processed->rain.rate, processed->barometer.current, processed->dew_point);
		fprintf(logfile, "%04d-%02d-%02d,%02d:%02d:%02d,%g,%g,%g,%g,%g,%g,%g,%s\n", utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec, processed->outdoor_temperature.current, processed->humidity.current, processed->barometer.current, processed->light.current, processed->rain.daily, processed->rain.rate, processed->wind.average_speed, processed->wind.average_direction);
		fflush(logfile);

		printf("updating wunderground...\n");
		curl_easy_setopt(curl, CURLOPT_URL, url);
		result = curl_easy_perform(curl);
		printf("done: %d\n", result);
		setup_mysql();
		snprintf(query, 512, "INSERT INTO `weather` ( `time` , `temperature` , `humidity` , `barometer` , `light` , `rain_daily` , `rain_rate` , `wind_speed_average` , `wind_direction_degrees` ) VALUES ('%04d-%02d-%02d %02d:%02d:%02d','%g','%g','%g','%g','%g','%g','%g','%g');", utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec, processed->outdoor_temperature.current, processed->humidity.current, processed->barometer.current, processed->light.current, processed->rain.daily, processed->rain.rate, processed->wind.average_speed, processed->wind.average_direction_degrees);

		if (mysql_query(&mysql, query) != 0)
		{
			printf("mysql error: %s\n", mysql_error(&mysql));
		}


		destroy_mysql();
		sleep(300);
	}
	fclose(logfile);
	curl_easy_cleanup(curl);
	pthread_exit(0);
}


