<?php

include "../Database.class";
include "../Functions.php";

//---------------------------------------------------------------------------------------------------------------- 
// INIT
//----------------------------------------------------------------------------------------------------------------  

  $Db = FN_DbOpen();
  
  $CR = "\n";

//---------------------------------------------------------------------------------------------------------------- 
// 
//----------------------------------------------------------------------------------------------------------------  
 
  //$Query  = "SELECT * FROM stations WHERE enable=1 AND done=0 AND source=".CONFIG_SOURCE_MARINE;
  $Query  = "SELECT * FROM stations WHERE enable=1 AND source=".CONFIG_SOURCE_MARINE;
  //echo "Query=".$Query.$CR;
  $ResultStations = $Db->Exec($Query);
  $TotRecStations = $Db->Numrows($ResultStations);
  echo "Stations to do=".$TotRecStations.$CR;
  //exit();
  
  // LIMITATORE DI CHIAMATE PER DEBUG
  //$TotRecStations = 10;
  
  $ApiError= 0; 
  
  for ($RecStations=0;$RecStations<$TotRecStations; $RecStations++)
  {
  	$RecordStations = $Db->Fetch($ResultStations, $RecStations);
	
	  $IDStation = $RecordStations["id"];
	  $Location = $RecordStations["location"];
	  $Source = $RecordStations["source"];
	  
	  echo $CR;
	  echo "Rec=".$RecStations."/".$TotRecStations.$CR;
	  echo "IDStation=".$IDStation.$CR;
	  echo "Location=".$Location.$CR;
	  echo "Source=".$Source.$CR;
	  //exit();
	  
	  $Url = CONFIG_WORLDWEATHERONLINE_URL."/v1/marine.ashx?q=".$RecordStations["latitude"].",".$RecordStations["longitude"]."&format=json&tide=yes&key=".CONFIG_WORLDWEATHERONLINE_KEY1;
	  //$Url = CONFIG_WORLDWEATHERONLINE_URL."/v1/ski.ashx?q=".$RecordStations["latitude"].",".$RecordStations["longitude"]."&format=json&includelocation=yes&key=".CONFIG_WORLDWEATHERONLINE_KEY;
	  echo "Url=".$Url.$CR;
	  
	  $Handle = @fopen($Url, "r");
	  
	  if ($Handle == FALSE)
	  {
	  	echo "Api non disponibili".$CR;
	  	SendError ("GetMarineStations", "Api non disponibili");
	  	$ApiError++;
	  	exit();
	  }
	  else
	  { 
	    $Json = "";
	      
	    while (TRUE)
	    { 
	    	$Block = fread($Handle, 1024);
	    	
	    	if (strlen($Block) == 0)
	    	{
	    		break;
	    	}
	    	
	    	$Json .= $Block;
	    } 
	    fclose($Handle);
	      
	    //echo "Json=".strlen($Json).$CR;
	      
	    $TabJson = json_decode($Json);
	      
	    //echo "TabJson=";
	    //print_r($TabJson);
	    //echo $CR.$CR;
	    //exit();
	                                      
	    $TabDate = $TabJson->data->weather;
      //echo "TabDate=";
	    //print_r($TabDate);
	    //echo $CR.$CR;
	    //exit();
	    
	    $LastUpdate = date("Y-m-d H:i:s");
	    echo "LastUpdate=".$LastUpdate.$CR;
	      
      for ($IndDate=0; $IndDate<count($TabDate); $IndDate++)
	    { 
	      $MeteoDate = $TabDate[$IndDate]->date;
	      
	      echo $CR; 
	      echo "MeteoDate=".$MeteoDate.$CR;
	      
	      
	      $TabTides = $TabDate[$IndDate]->tides[0]->tide_data;
	      //echo "TabTides=";
	      //print_r($TabTides);
	      //echo $CR.$CR;
	      
	      $TabHeightTides = array();
	      
	      for ($Ind=0; $Ind<count($TabTides); $Ind++)
		    { 
		      $Tide = $TabTides[$Ind];
		          
		      //echo "tideTime=".$Tide->tideTime."-".$CR;
          //echo "tideHeight_mt=".$Tide->tideHeight_mt.$CR;
		      //exit();
		         
		      switch ($Tide->tideTime)
		      {
		      case "01:00 AM":
		        $TabHeightTides["00:00:00"] = $Tide->tideHeight_mt;
		        break;
		      case "04:00 AM":
		        $TabHeightTides["03:00:00"] = $Tide->tideHeight_mt;
		        break;
		      case "07:00 AM":
		        $TabHeightTides["06:00:00"] = $Tide->tideHeight_mt;
		        break;
		      case "10:00 AM":
		        $TabHeightTides["09:00:00"] = $Tide->tideHeight_mt;
		        break;
		      case "01:00 PM":
		        $TabHeightTides["12:00:00"] = $Tide->tideHeight_mt;
		        break;
		      case "04:00 PM":
		        $TabHeightTides["15:00:00"] = $Tide->tideHeight_mt;
		        break;
		      case "07:00 PM":
		        $TabHeightTides["18:00:00"] = $Tide->tideHeight_mt;
		        break;
		      case "10:00 PM":
		        $TabHeightTides["21:00:00"] = $Tide->tideHeight_mt;
		        $TabHeightTides["23:00:00"] = $Tide->tideHeight_mt;
		        break;
		      }                                  
		 	  } 	
		      	  
		    //echo "TabHeightTides=";
		    //print_r($TabHeightTides);
		    //echo $CR.$CR;
		    //exit();
        
	      
	      $TabWeathers = $TabDate[$IndDate]->hourly;
	      //echo "TabWeathers=".count($TabWeathers).$CR;
	      
		    for ($Ind=0; $Ind<count($TabWeathers); $Ind++)
		    { 
		      $Weather = $TabWeathers[$Ind];
		          
		      switch ($Weather->time)
		      {
		      case 0:
		        $MeteoTime = "00:00:00";
		        break;
		      case 300:
		        $MeteoTime = "03:00:00";
		        break;
		      case 600:
		        $MeteoTime = "06:00:00";
		        break;
		      case 900:
		        $MeteoTime = "09:00:00";
		        break;
		      case 1200:
		        $MeteoTime = "12:00:00";
		        break;
		      case 1500:
		        $MeteoTime = "15:00:00";
		        break;
		      case 1800:
		        $MeteoTime = "18:00:00";
		        break;
		      case 2100:
		        $MeteoTime = "21:00:00";
		        break;
		      case 2300:
		        $MeteoTime = "23:00:00";
		        break;
		      }                                  
		      echo "MeteoTime=".$MeteoTime.$CR;
		      	  
		      $WeatherCode   = $Weather->weatherCode;
		      $Cloudcover    = $Weather->cloudcover;
		      $Temperature   = $Weather->tempC;
		      $Humidity      = $Weather->humidity;
		      $Rainfall      = $Weather->precipMM;
		      $Pressure      = $Weather->pressure;
		      $Visibility    = $Weather->visibility;
		      	    	  
		      $WindCode      = $Weather->winddir16Point;
          $WindDegree    = $Weather->winddirDegree;
		      $WindSpeed     = $Weather->windspeedKmph;
		      	    	  
		      $SwellDegree   = $Weather->swellDir;
          $SwellHeight   = $Weather->swellHeight_m;
          $SwellPeriod   = $Weather->swellPeriod_secs;
		      	    	  
		      $WaterTemp    = $Weather->waterTemp_C;
		      $TideHeight   = $TabHeightTides[$MeteoTime];
		      	    	  
/*      
		      echo "WeatherCode=".$WeatherCode.$CR;
		      echo "Cloudcover=".$Cloudcover.$CR;
		      echo "Visibility=".$Visibility.$CR;
		      	    	  
		      echo "Temperature=".$Temperature.$CR;
		      echo "Humidity=".$Humidity.$CR;
		      echo "Rainfall=".$Rainfall.$CR;
		      echo "Pressure=".$Pressure.$CR;
		      
		      echo "WindCode=".$WindCode.$CR;
		      echo "WindDegree=".$WindDegree.$CR;
		      echo "WindSpeed=".$WindSpeed.$CR;
		      
		      echo "SwellDegree=".$SwellDegree.$CR;
		      echo "SwellHeight=".$SwellHeight.$CR;
		      echo "SwellPeriod=".$SwellPeriod.$CR;
		      
		      echo "WaterTemp=".$WaterTemp.$CR;
		      echo "TideHeight=".$TideHeight.$CR;
		      //exit();
*/      
        
		      $Query = "SELECT * FROM meteo WHERE id_station=".$IDStation." AND datetime='".$MeteoDate." ".$MeteoTime."'";
		      $Result = $Db->Exec($Query);
	        $TotRec = $Db->NumRows($Result);
		      if ($TotRec == 0)
		      {
		        $Query  = "INSERT INTO meteo (id_station, lastupdate, datetime, weather_code, cloudcover_code, visibility_code, temperature, humidity, rainfall, pressure, ";
		        $Query .= "wind_code, wind_degree, wind_speed, swell_degree, swell_height, swell_period, water_temperature, tide_height) VALUES (";
		        $Query .= $IDStation.", ";
		        $Query .= "'".$LastUpdate."', ";
		        $Query .= "'".$MeteoDate." ".$MeteoTime."', ";
		        $Query .= $WeatherCode.", ";
		        $Query .= $Cloudcover.", ";
		        $Query .= $Visibility.", ";
		        $Query .= "'".$Temperature."', ";
		        $Query .= "'".$Humidity."', ";
		        $Query .= "'".$Rainfall."', ";
		        $Query .= $Pressure.", ";
		        $Query .= "'".$WindCode."', ";
		        $Query .= $WindDegree.", ";
		        $Query .= "'".$WindSpeed."', ";
		        $Query .= $SwellDegree.", ";
		        $Query .= "'".$SwellHeight."', ";
		        $Query .= "'".$SwellPeriod."', ";
		        $Query .= "'".$WaterTemp."', ";
		        $Query .= "'".$TideHeight."')";
		      }
		      else
		      {
		        $Record = $Db->Fetch($Result, 0);
		        
		        $Query  = "UPDATE meteo SET ";
		        $Query .= "lastupdate='".$LastUpdate."', ";
		        $Query .= "weather_code=".$WeatherCode.", ";
		        $Query .= "cloudcover_code=".$Cloudcover.", ";
		        $Query .= "visibility_code=".$Visibility.", ";
		        $Query .= "temperature='".$Temperature."', ";
		        $Query .= "humidity='".$Humidity."', ";
		        $Query .= "rainfall='".$Rainfall."', ";
		        $Query .= "pressure=".$Pressure.", ";
		        $Query .= "wind_code='".$WindCode."', ";
		        $Query .= "wind_degree=".$WindDegree.", ";
		        $Query .= "wind_speed='".$WindSpeed."', ";
		        $Query .= "swell_degree=".$SwellDegree.", ";
		        $Query .= "swell_height='".$SwellHeight."', ";
		        $Query .= "swell_period='".$SwellPeriod."', ";
		        $Query .= "water_temperature='".$WaterTemp."', ";
		        $Query .= "tide_height='".$TideHeight."' ";    
		        $Query .= "WHERE id_station=".$IDStation." AND datetime='".$MeteoDate." ".$MeteoTime."'";
		      }
		      //echo "Query=".$Query.$CR;
		      $Db->Exec($Query);
		      //exit(); 
        }
      }
      $Query  = "UPDATE stations SET done=1 WHERE id=".$IDStation;
      //echo "Query=".$Query.$CR;
		  $Db->Exec($Query);
	  }  
	  sleep(1);
	  //exit();
  }	
  
  $Db->Close();
  
  //mail("fishwolf@gmail.com", "GetMarineStations", "ApiError=".$ApiError, "Header");
  SendError ("GetMarineStations", "ApiError=".$ApiError);
  
?>