<?php
/**
 * Handler for the Weather module.
 *
 * @url         $URL: svn+ssh://ijr@cvs.mythtv.org/var/lib/svn/trunk/mythplugins/mythweb/modules/weather/handler.php $
 * @date        $Date: 2006-04-02 03:40:11 -0400 (Sun, 02 Apr 2006) $
 * @version     $Revision: 9601 $
 * @author      $Author: xris $
 * @license     GPL
 *
 * @package     MythWeb
 * @subpackage  Weather
 *
/**/

// Unit preference
    if (empty($_SESSION['siunits'])) {
        $_SESSION['siunits'] = setting('SIUnits');
    }

/**
 * @global  array   $GLOBALS['Weather_Types']
 * @name    $Weather_Types
/**/
    global $Weather_Types;
    $Weather_Types = array();

// Load the weather data
    foreach (file(modules_path.'/'.module.'/weathertypes.dat') as $line) {
        list($id, $name, $img) = explode(',', $line);
        $Weather_Types[$id] = array($img, $name);
    }

// Build a list of the known weather sites
    $WeatherSites = array();

    $sh = $db->query('SELECT data, hostname FROM settings WHERE value="locale"');
    while (list($data, $host) = $sh->fetch_row()) {
    // New data site
        if (empty($WeatherSites[$data])) {
            $WeatherSites[$data] = new WeatherSite($data, $hostname, $_SESSION['siunits']);
        }
    // Add the hostname to sites we've already seen
        else {
            $WeatherSites[$data]->host .= ', '.$host;
        }

    }
    $sh->finish();

// Print the weather page template
    require_once tmpl_dir.'weather.php';

// Exit
    exit;

class WeatherSite {

    var $acid;
    var $host;

    var $city;
    var $subdiv;
    var $country;
    var $region;

    var $use_metric;
    var $Temperature;
    var $CIcon;
    var $ConditionImage;
    var $ConditionText;
    var $WindSpeed;
    var $WindDirection;
    var $BarometricPressure;
    var $Humidity;
    var $Real;
    var $UV;
    var $Visibility;
    var $ConText;
    var $Forecast;

    var $RadarImage;

    var $LastUpdated;

    var $Sunrise;
    var $Sunset;

    function WeatherSite($data, $hostname, $use_metric) {
        $this->acid       = $data;
        $this->host       = $hostname;
        $this->use_metric = $use_metric;

        $this->getData();
        $this->RadarImage = $this->getRadarURL();
    }

    function getData() {
$myfile = fopen("/tmp/weather", "w");

    //$data = file("http://www.msnbc.com/m/chnk/d/weather_d_src.asp?acid=" . $this->acid);
    $data = file("http://xml.weather.yahoo.com/forecastrss?p=" . $this->acid);

    //$xml = simplexml_load_file("http://xml.weather.yahoo.com/forecastrss?p=" . $this->acid);
    $xml = simplexml_load_string(implode("\n",$data));

fwrite($myfile, "xml = ".print_r($xml,TRUE)."\n");
    $this->LastUpdated = implode(',', $xml->xpath("//lastBuildDate"));
    $this->city = implode(',', $xml->xpath('//yweather:location/@city'));
    $this->subdiv = implode(',', $xml->xpath("//yweather:location/@region"));
    $this->country = implode(',', $xml->xpath("//yweather:location/@country"));
    $this->region = implode(',', $xml->xpath("//yweather:location/@region"));
    $this->Real = implode(',', $xml->xpath("//yweather:wind/@chill"));
    $dir_str = array('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N');
    $temp = $xml->xpath("//yweather:wind/@direction");
    $this->WindDirection = $dir_str[($temp[0] - 22.5) / 45 ];
    $this->WindSpeed = implode(',', $xml->xpath("//yweather:wind/@speed"));
    $this->Humidity=implode(',',$xml->xpath("//yweather:atmosphere/@humidity"));
    $this->Visibility = implode(',',
		$xml->xpath("//yweather:atmosphere/@visibility")) / 100;
    $this->BarometricPressure = implode(',', 
		$xml->xpath("//yweather:atmosphere/@pressure"));
    $this->Sunrise = implode(',', $xml->xpath("//yweather:astronomy/@sunrise"));
    $this->Sunset = implode(',', $xml->xpath("//yweather:astronomy/@sunset"));
    $this->ConText = implode(',', $xml->xpath("//yweather:condition/@text"));
    $this->Temperature=implode(',', $xml->xpath("//yweather:condition/@temp"));
    //$this->LastUpdated=implode(',',$xml->xpath("//yweather:condition/@date"));
    //$this->CIcon = implode(',', $xml->xpath("//img/@src"));
    //$this->UV = implode(',', $xml->xpath("//@unknown"));
$temp = implode('|', $xml->xpath("//yweather:forecast/@*"));
fwrite($myfile, "data = ".print_r($temp,TRUE)."\n");
    $this->Forecast = $this->readForecast(
		implode('|', $xml->xpath("//yweather:forecast/@*")));

fwrite($myfile, "this = ".print_r($this,TRUE)."\n");
fclose($myfile);


    foreach($data as $line) {
        //if(strpos($line, "this.sw") === false)
        if(strpos($line, "yweather:") === false)
        continue;
        //if(strpos($line, "swTempCel") !== false)
        //continue;

        $line = trim($line);
        list($name, $value) = explode(" = \"", $line);
        $name = substr($name, 7);
        $value = substr($value, 0, strlen($value) - 2);

        switch ($name) {
        default:
           // Weird, unknown type
           break;
        }
    }

    //Are we using metric or imperial system
    if($this->use_metric == "YES") {
        $this->Temperature = round((5/9) * ($this->Temperature - 32));
        $this->Real = round((5/9) * ($this->Real - 32));
        $this->BarometricPressure = round($this->BarometricPressure * 2.54);
        $this->Visibility = round($this->Visibility * 1.609344);
        $this->WindSpeed = round($this->WindSpeed * 1.609344);
    }

    if(strlen($this->ConText) > 0) {
        $this->ConditionText = $this->ConText;
        $this->ConditionImage = getImageFromName($this->ConditionText);
        if(strlen($this->ConditionImage) == 0)
        list($this->ConditionImage, $blah) = getImageAndDescFromId($this->CIcon);
    } else {
        list($this->ConditionImage, $this->ConditionText) = getImageAndDescFromId($this->CIcon);
    }
    $this->ConditionImage = (strlen($this->ConditionImage) > 0) ? $this->ConditionImage : "unknown.png";
    }

    function getRadarURL() {
    $data = file("http://www.weather.com/weather/map/" . $this->acid . "?from=LAPmaps&setcookie=1");
    foreach($data as $line) {
        if(substr(trim($line), 0, 29) != "if (isMinNS4) var mapNURL = \"") continue;

        $url1 = substr(trim($line), 30);
        $url1 = "http://www.weather.com/" . substr($url1, 0, strlen($url1) - 2);

        break;
    }

    $data = file($url1);
    foreach($data as $line) {
        if(substr(trim($line), 0, 48) != "<IMG NAME=\"mapImg\" SRC=\"http://image.weather.com") continue;

        $url2 = substr(trim($line), 24);
        $url2 = substr($url2, 0, strpos($url2, '"'));
        break;
    }
    return $url2;
    }

    function readForecast($data) {
    $ret = array();

    $data = explode("|", $data);
    for($i = 0;$i<count($data);$i+=6) {
	$dayofweek = $data[$i];
        $forecast = new Forecast($data[1 + $i],$dayofweek);
        //$forecast->dayofweek = $dayofweek;
        list($forecast->DescImage,$forecast->DescText) = getImageAndDescFromId($data[5 + $i]);
        $forecast->DescImage = (strlen($forecast->DescImage) > 0) ? $forecast->DescImage : "unknown.png";
        $forecast->DescText = (strlen($forecast->DescText) > 0) ? $forecast->DescText : t('Unknown') . " (" . $data[5+$i] . ")";
        $forecast->DescText = $forecast->DescText."<p>(".$data[5+$i]." - ".$data[4+$i].")";
        if($this->use_metric == "YES") {
            $forecast->HighTemperature = round((5/9) * ($data[3 + $i] - 32));
            $forecast->LowTemperature = round((5/9) * ($data[2 + $i] -32 ));
        } else {
        $forecast->HighTemperature = $data[3 + $i];
        $forecast->LowTemperature = $data[2 + $i];
        }

        $ret[$i / 6] = $forecast;
    }

    return $ret;
    }
}

function getImageAndDescFromId($my_id) {
    global $Weather_Types;
    return $Weather_Types[$my_id];
}

function getImageFromName($my_name) {
    global $Weather_Types;
    foreach ($Weather_Types as $pair) {
        if ($pair[1] == $my_name)
            return $pair[0];
    }
}

class Forecast {
    var $date;
    var $dayofweek;

    var $DescImage;
    var $DescText;

    var $HighTemperature;
    var $LowTemperature;

    function Forecast($date,$real_dayofweek) {

    //$date_time_array = date_parse($date);
    $date_time_array = getdate(strtotime($date));
    $month = $date_time_array["month"];
    $day = $date_time_array["day"];
    $year = $date_time_array["year"];

    //$temp_date = mktime(0,0,0,$month,$day,$year);
    //$date_time_array = getdate( $temp_date );
    $claimed_dayofweek = $date_time_array['weekday'];
    $this->dayofweek = $date_time_array['wday'];

    $this->date = $date;

    //if($real_dayofweek != $claimed_dayofweek)
    //    $this->date = date("m/d/Y", mktime(0, 0, 0, $month, $day, $year));
    //else
    //    $this->date = $date;
    }
}
