<?php

// Freetz Weather Server
// Alexey Ozerov (c) 2013
// GNU GENERAL PUBLIC LICENSE
// Ver. 1.17

// Configuration

$db_host='localhost';
$db_name='frewe';
$db_user='frewe';
$db_pass='frewe_2014';
$db_table='frewe_history';




// timechart
ini_set('include_path', 'timechart/libs');
// include the main timechart library
require_once('timechart.class.php');

$chart="";
if (isset($_GET["chart"]) && ( $_GET["chart"]=="temp" || $_GET["chart"]=="rain"  || $_GET["chart"]=="hum" || $_GET["chart"]=="winddeg" || $_GET["chart"]=="wind" || $_GET["chart"]=="press" || $_GET["chart"]=="windavg") )
   $chart = $_GET["chart"];

if (!isset($_GET["start"]))
  $start="-7d";
else
  $start=$_GET["start"];

if (isset($_GET["fromdate"]))
  $fromdate=$_GET["fromdate"];
if (isset($_GET["todate"]))
  $todate=$_GET["todate"];

if(strlen($chart)==0){

echo"<html>
<head>
</head>
<body>
<p>Regenerating charts 
";
}

//********************************************************************
// DO NOT EDIT BELOW THIS LINE
//********************************************************************

// Swith to test table on test installation

if (strstr($_SERVER['PHP_SELF'],'test-frewe-server.php'))
	$db_table = 'test_frewe_history';

// Check server key

//if (!isset($_GET["serverkey"]) || $_GET["serverkey"]!=$serverkey || $_GET["serverkey"]=="")
//	error('Frewe ERROR: wrong or empty server key');

// Open mySQL

$link = mysql_connect($db_host, $db_user, $db_pass);
if (!$link)
	error('Frewe ERROR: mySQL fault: ' . mysql_error());

$db_selected = mysql_select_db($db_name, $link);
if (!$db_selected)
	error('Frewe ERROR: Database selection fault: ' . mysql_error());

$query = "SELECT CONVERT_TZ(`datetime`,'+00:00','+02:00') as datetime FROM $db_table ORDER BY `datetime` ASC LIMIT 1";
#$query = "SELECT datetime FROM $db_table ORDER BY `datetime` ASC LIMIT 1";

$result = mysql_query($query,$link);
if (!$result)
	error('Frewe ERROR dabase query fault: ' . mysql_error(). ' query: '. $query);
$lastrow = mysql_fetch_assoc($result);
if ($lastrow)
	$firsttimestamp = strtotime($lastrow['datetime']);
else
	$firsttimestamp = NULL;
// Get last datetime



$query = "SELECT CONVERT_TZ(`datetime`,'+00:00','+02:00') as datetime FROM $db_table ORDER BY `datetime` DESC LIMIT 1";
#$query = "SELECT datetime FROM $db_table ORDER BY `datetime` DESC LIMIT 1";

$result = mysql_query($query,$link);
if (!$result)
	error('Frewe ERROR dabase query fault: ' . mysql_error(). ' query: '. $query);
$lastrow = mysql_fetch_assoc($result);
if ($lastrow){
	$lasttime = $lastrow['datetime'];
	$lasttimestamp = strtotime($lastrow['datetime']);
}else{
	$lasttime = NULL;
		$lasttimestamp = NULL;
}

$lasttimestamp=strtotime($lasttime);

$starttimestamp=0;

if($fromdate & $todate){

$starttimestamp=strtotime($fromdate." 00:00:00");
$stoptimestamp=strtotime($todate." 23:59:59");

} else {

if($start=='-1d')
  $starttimestamp=$lasttimestamp-24*60*60;
else if($start=='-7d')
  $starttimestamp=$lasttimestamp-7*24*60*60;
else if($start=='-28d')
  $starttimestamp=$lasttimestamp-28*24*60*60;
else if($start=='all')
  $starttimestamp=$firsttimestamp;

$stoptimestamp=$lasttimestamp;
}

$starttimestamp=max($firsttimestamp,$starttimestamp);

/*
echo "
<pre>
";
print_r($starttimestamp);
print_r($stoptimestamp);
echo "
</pre>
";
*/

// Get data

$query = "SELECT CONVERT_TZ(datetime,'+00:00','+02:00') as datetime ,humin,humout,tempin,tempout,tempchill,tempdew,windspeed,windgust,winddir,winddeg,pressabs,pressrel,raindif,illu,uv FROM $db_table WHERE datetime>='".date("Y-m-d H:i:s",$starttimestamp)."' AND datetime<='".date("Y-m-d H:i:s",$stoptimestamp)."' ORDER BY datetime ASC";

$result = mysql_query($query,$link);

$humin = array();
$humout = array();
$tempin = array();
$tempout = array();
$tempchill = array();
$tempdew = array();
$windspeed = array();
$windgust = array();
$winddir = array();
$winddeg = array();
$pressabs = array();
$pressrel = array();
$rain = array();
$illu = array();
$uv = array();


if (!$result)
	error('Frewe ERROR dabase query fault: ' . mysql_error(). ' query: '. $query);
while ( $data = mysql_fetch_assoc($result) ){
$timestamp=strtotime($data['datetime']);

//if($timestamp>=$starttimestamp){

  $humin[$timestamp] = $data['humin'];
  $humout[$timestamp] = $data['humout'];
  $tempin[$timestamp] = $data['tempin'];
  $tempout[$timestamp] = $data['tempout'];
  $tempchill[$timestamp] = $data['tempchill'];
  $tempdew[$timestamp] = $data['tempdew'];
  $windspeed[$timestamp] = $data['windspeed'];
  $windgust[$timestamp] = $data['windgust'];
  $winddir[$timestamp] = $data['winddir'];
  $winddeg[$timestamp] = $data['winddeg'];
  $pressabs[$timestamp] = $data['pressabs'];
  $pressrel[$timestamp] = $data['pressrel'];
  if($data['raindif']>=0) {
    $rain[$timestamp] = $data['raindif'];
  } else {
    $rain[$timestamp] = 0;
  }
  $illu[$timestamp] = $data['illu'];
  $uv[$timestamp] = $data['uv'];
  /*
	echo "
	<pre>
	";
	print_r($timestamp);
	echo "
	</pre>
	";
  */

if(strlen($chart)==0){
echo " . ";
}
//}
}
/*	echo "
	<pre>
	";
	print_r($tempout);
	echo "
	</pre>
	";
*/

if(strlen($chart)==0){
echo "
</p>
";
}

// create colors
$cg = new ColorGenerator();
$c = $cg->getColors(6);

if(strlen($chart)==0){
// create the chart (default - linear transformations for both axes)
$chartT = new TimeChart('Temperatur (°C)', null, null, false);
// add the data to chart
$chartT->addData('aussen',        $tempout, $c[0], TimeChart::SQUARE);
$chartT->addData('innen',        $tempin, $c[1], TimeChart::SQUARE);
//$chartT->addData('tempchill',        $tempchill, $c[2], TimeChart::SQUARE);
$chartT->addData('Taupunkt',        $tempdew, $c[3], TimeChart::SQUARE);
// render the chart
$chartT->output(1100, 600, null, 'tmp/temp.png');


// create the chart (default - linear transformations for both axes)
$chartH = new TimeChart('Luftfeuchtigkeit (%)', null, null, false,false,0,100,11);
// add the data to chart
$chartH->addData('aussen',        $humout, $c[0], TimeChart::SQUARE);
$chartH->addData('innen',        $humin, $c[1], TimeChart::SQUARE);
// render the chart
$chartH->output(1100, 600, null, 'tmp/hum.png');


// create the chart (default - linear transformations for both axes)
$chartW = new TimeChart('Windgeschwindigkeit (km/h)', null, null, false);
// add the data to chart
$chartW->addData('Wind',        $windspeed, $c[0], TimeChart::SQUARE);
$chartW->addData('Boeen',        $windgust, $c[1], TimeChart::SQUARE);
// render the chart
$chartW->output(1100, 600, null, 'tmp/wind.png');

// create the chart (default - linear transformations for both axes)
$chartP = new TimeChart('Luftdruck (hPa)', null, null, false);
// add the data to chart
$chartP->addData('rel.',        $pressrel, $c[0], TimeChart::SQUARE);
// render the chart
$chartP->output(1100, 600, null, 'tmp/press.png');

// create the chart (default - linear transformations for both axes)
$chartR = new TimeChart('Regen (mm)', null, null, false);
// add the data to chart
$sumAggregator  = new SumAggregator(SumAggregator::HOUR); 
$rainsum = $sumAggregator->process($rain);
$diffProcessor  = new DiffProcessor(); 
// TODO: use $rainsum
$raindiff = $diffProcessor->process($rain);
$chartR->addData('Regen',        $rain, $c[0], TimeChart::SQUARE);
// render the chart
$chartR->output(1100, 600, null, 'tmp/rain.png');

echo"
<p>
Files written.
</p>
<p>
<a href='index-files.html'>Continue ...</a>
</body>
</html>
";
} else {
if($chart=="temp"){
// create the chart (default - linear transformations for both axes)
$chartT = new TimeChart('Temperatur (°C)', null, null, false);
// add the data to chart
$chartT->addData('aussen (aktuell '.round($tempout[$lasttimestamp],1).'°C)',        $tempout, $c[0], TimeChart::SQUARE);
$chartT->addData('innen (aktuell '.round($tempin[$lasttimestamp],1).'°C)',        $tempin, $c[1], TimeChart::SQUARE);
//$chartT->addData('tempchill',        $tempchill, $c[2], TimeChart::SQUARE);
$chartT->addData('Taupunkt (aktuell '.round($tempdew[$lasttimestamp],1).'°C)',        $tempdew, $c[3], TimeChart::SQUARE);
// render the chart
header("Content-type: image/png");
$chartT->output(1100, 600, null, null);
/*
header("Content-type: text/html");
	echo "
	<pre>
	";
	print_r($query);
	print_r($timestamp);
	print_r($tempout);
	echo "
	</pre>
	";
*/
} else if($chart=="hum"){
// create the chart (default - linear transformations for both axes)
$chartH = new TimeChart('Luftfeuchtigkeit (%)', null, null, false, true, 0,100,11);
// add the data to chart
$chartH->addData('aussen (aktuell '.round($humout[$lasttimestamp],1).'%)',        $humout, $c[0], TimeChart::SQUARE);
$chartH->addData('innen (aktuell '.round($humin[$lasttimestamp],1).'%)',        $humin, $c[1], TimeChart::SQUARE);
// render the chart
header("Content-type: image/png");
$chartH->output(1100, 600, null, null);

} else if($chart=="winddeg"){

// create the chart (default - linear transformations for both axes)
$chartW = new TimeChart('Windrichtung', null, null, false, false, 0, 360, 9);
// add the data to chart
$chartW->addData('Windrichtung (aktuell '.round($winddeg[$lasttimestamp],1).'Grad)',        $winddeg, $c[0], TimeChart::SQUARE);
// render the chart
header("Content-type: image/png");
$chartW->output(1100, 600, null, null);
/*
header("Content-type: text/html");
	echo "
	<pre>
	";
	print_r($query);
	print_r($timestamp);
	print_r($winddeg);
	echo "
	</pre>
	";
*/
} else if($chart=="wind"){

// create the chart (default - linear transformations for both axes)
$chartW = new TimeChart('Windgeschwindigkeit (km/h)', null, null, false);
// add the data to chart
$chartW->addData('Wind (aktuell '.round($windspeed[$lasttimestamp],1).'km/h)',        $windspeed, $c[0], TimeChart::SQUARE);
$chartW->addData('Boeen (aktuell '.round($windgust[$lasttimestamp],1).'km/h)',        $windgust, $c[1], TimeChart::SQUARE);
// render the chart
header("Content-type: image/png");
$chartW->output(1100, 600, null, null);

} else if($chart=="windavg"){

// create the chart (default - linear transformations for both axes)
$chartWA = new TimeChart('Windgeschwindigkeit (km/h) Stundenmittel', null, null, false);
$averagingAggregator  = new AveragingAggregator(AveragingAggregator::HOUR); 
$windspeedavg = $averagingAggregator->process($windspeed);
$windgustavg = $averagingAggregator->process($windgust);
// add the data to chart
$chartWA->addData('Wind (aktuell '.round(end($windspeedavg),1).'km/h)',        $windspeedavg, $c[2], TimeChart::CROSS);
$chartWA->addData('Boeen (aktuell '.round(end($windgustavg),1).'km/h)',        $windgustavg, $c[3], TimeChart::CROSS);
// render the chart
header("Content-type: image/png");
$chartWA->output(1100, 600, null, null);

} else if($chart=="press"){
// create the chart (default - linear transformations for both axes)
$chartP = new TimeChart('Luftdruck (hPa)', null, null, false);
// add the data to chart
$chartP->addData('rel. (aktuell '.round($pressrel[$lasttimestamp],1).'hPa)',        $pressrel, $c[0], TimeChart::SQUARE);
// render the chart
header("Content-type: image/png");
$chartP->output(1100, 600, null, null);

} else if($chart=="rain"){
// create the chart (default - linear transformations for both axes)
$chartR = new TimeChart('Regen (mm/h) ', null, null, false);
// add the data to chart
$sumAggregator  = new SumAggregator(SumAggregator::HOUR); 
$rainsum = $sumAggregator->process($rain);
//$chartR->addData('Regen (aktuell '.$raindiff[$lasttimestamp].')',        $raindiff, $c[0], TimeChart::SQUARE);
$chartR->addData('Regen (aktuell '.round(end($rainsum),1).'mm)',        $rainsum, $c[0], TimeChart::SQUARE);
// render the chart
header("Content-type: image/png");
$chartR->output(1100, 600, null, null);
}
}

// *********************************************************
// Log error and exit
// *********************************************************

function error($message)
{
	global $link;
	if ($link) mysql_close($link);

	error_log ($message);
	echo ($message);
	exit(1);
}

?>
