#!/usr/bin/perl
$|++;
$live=1;
@mdays=qw(0 31 29 31 30 31 30 31 31 30 31 30 31);
@months=qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@algos=qw(fm_ht_sssr nm_ht_sssr algo_mt_sssr_ht_nmfm);
#@locations=("Wellington Harbour");
use DBI;
use CGI;
use SVG::TT::Graph::Line;


## determine what today is
(undef,undef,undef,$myday,$mymonth,$myyear,undef,undef,undef)=localtime(time);
$mymonth++;
$myyear=1900+$myyear;


$db=DBI->connect('dbi:mysql:fishing','root','j3nn0f3r') or die "Unable to connect to database.\n";

$rq=$db->prepare("select distinct location from locations order by location");
$rq->execute();
$la=$rq->fetchall_arrayref;
$rq->finish();
foreach $lar (@$la) {
	my ($loc)=@$lar;
	push @locations,$loc;
}




$q=new CGI;
$targetmonth=$q->param("targetmonth");
$targetyear=$q->param("targetyear");
$algo=$q->param("algo");
$location=$q->param("location");

if ( ($targetmonth eq "") || ($targetyear eq "") ) {
	(undef,undef,undef,undef,$targetmonth,$targetyear,undef,undef,undef)=localtime(time);
	$targetmonth++;
	$targetyear=1900+$targetyear;
	print STDERR "Setting default month and year to $targetmonth $targetyear\n";
	$algo="fm_ht_sssr";
	$location="Wellington Harbour";
}

use POSIX;

require "/var/www/fishing/moonsubs.pm";
require "/var/www/fishing/subs.pm";

($latdec,$longdec,$latword,$longword)=getLocation($location);

my $lat = deg2rad ($latdec);    # Radians
my $long = deg2rad ($longdec);  # Radians
my $alt = 0.01;        # Kilometers
my $moon = Astro::Coord::ECI::Moon->new ();
my $sun = Astro::Coord::ECI::Sun->new ();

$dblocation=$db->quote($location);

$rq=$db->prepare("select day,month,year,dst,time,meansize from tide where location=$dblocation and month=$targetmonth and year=$targetyear");
$rq->execute();
$ar=$rq->fetchall_arrayref;
$rq->finish();

$rows=scalar(@$ar);
if ($rows == 0) {
	use WWW::Mechanize;
	use HTTP::Cookies;
	use HTML::Form::ForceValue;
	$dpm=@mdays[$targetmonth];
	$mech=WWW::Mechanize->new();
	$mech->cookie_jar(HTTP::Cookies->new());
	$mech->get("http://www.niwa.co.nz/our-services/online-services/tides");
	$mech->form_name('tide_input');
	$mech->field(location_name => '[User Defined Location]');
	$mech->field(loc => '0');
	$mech->field(lat => $latword);
	$mech->field(lon => $longword);
	$mech->field(datum => 'MSL');
	$mech->form_name('tide_input')->find_input('days')->force_value($dpm);
#	$mech->field(days => $dpm);
	$mech->field(day => '1');
	$mech->field(month => $targetmonth);
	$mech->field(year => $targetyear);
	$mech->field(time => '12');
	$mech->field(showResults => 'data');
	$mech->field(submitbutton => 'Calculate');
	$mech->click();
	$content=$mech->content();
	open F,">/tmp/htmldelivered";
	print F $content;
	close F;

	if ($content ne "") {
		stripTable($content);
	} else {
		print "$content\n";
		die("Cannot get data from niwa.\n");
	}

#	use LWP::UserAgent;
#	use HTTP::Cookies;
#	my $ua = new LWP::UserAgent;
#	$dpm=@mdays[$targetmonth];
#	my $cookie_jar;
#	$ua->cookie_jar(HTTP::Cookies->new());
#	$ua->agent("Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.6) Gecko/2009011912 Firefox/3.0.6");
#	$duh=$ua->get("http://www.niwa.co.nz/our-services/online-services/tides");
#	print STDERR "$cookie_jar\n";
#	my $res =$ua->post('http://www.niwa.co.nz/services/free/tides/results',
#            [
#                'location_name' => "[User Defined Location]",
#                'loc' => "0",
#              'lat' => $latword,
#              'lon' => $longword,
#                'datum' => 'MSL',
#                'days' => $dpm,
#                'day' => '1',
#                'month' => $targetmonth,
#                'year' => $targetyear,
#                'time' => '12',
#                'showResults' => 'data',
#                'submitbutton' => 'Calculate'
#                ],
#           );
#
#	 if ($res->is_success) {
#	        $d = $res->content;
#	 } else {
#		die ("Cannot get data from niwa.\n");
#	 }
#	stripTable($d);

#	$rq=$db->prepare("select day,month,year,dst,time,meansize from tide where location=$dblocation and month=$targetmonth and year=$targetyear");
#	$rq->execute();
#	$ar=$rq->fetchall_arrayref;
#	$rq->finish();



	
}

$rq=$db->prepare("select day,month,year,sunrise,sunset,moonphase,moon_svis,moonrise,moonset,moonmeridian from astro where location=$dblocation and month=$targetmonth and year=$targetyear");
$rq->execute();
$ar2=$rq->fetchall_arrayref;
$rq->finish();

$rows=scalar(@$ar2);
if ($rows == 0) {
	use Astro::Coord::ECI;
	use Astro::Coord::ECI::Moon;
	use Astro::Coord::ECI::Utils qw{deg2rad};
	use Astro::Sunrise;
	use Date::Parse;
	use Date::Manip;

	$rq=$db->prepare("select day,dst from tide where location=$dblocation and month=$targetmonth and year=$targetyear group by day order by day");
	$rq->execute();
	$ar3=$rq->fetchall_arrayref;
	$rq->finish();
	foreach $arf3 (@$ar3) {
		my ($day,$dst)=@$arf3;
		$secs = UnixDate("$targetmonth/$day/$targetyear 00:00","%s");
		($phase,$visible)=putmoon($secs);
		$dbphase=$db->quote($phase);
		$offset=12;
		if ($dst == 1) {
			$offset=13;
		}
		($sunrise, $sunset) = sunrise($targetyear,$targetmonth,$day, $longdec,$latdec,$offset,0 );
		($h,$m)=split(':',$sunrise);
                $sunrise=($h*60)+$m;
		($h,$m)=split(':',$sunset);
                $sunset=($h*60)+$m;

		@almanac = $moon->almanac (Astro::Coord::ECI->geodetic ($lat, $long, $alt), $secs, $secs+86400);
		$moonrise=$moonset=$meridian=-1;
		foreach my $foo (@almanac) {
			my ($utime,$event,$detail,$desc)=@$foo;
			if ($dst == 1) {
				$utime=$utime+3600; ## local DST offset
			}
			if ($desc eq "Moon transits meridian") {
				$meridian=int(($utime-$secs)/60);
			} elsif ($desc eq "Moon rise") {
				$moonrise=int(($utime-$secs)/60);
			} elsif ($desc eq "Moon set") {
				$moonset=int(($utime-$secs)/60);
			}
		}


		$db->do("insert into astro (location,day,month,year,sunrise,sunset,moonphase,moon_svis,moonrise,moonset,moonmeridian) values ($dblocation,$day,$targetmonth,$targetyear,$sunrise,$sunset,$dbphase,$visible,$moonrise,$moonset,$meridian)");

	}
	$rq=$db->prepare("select day,month,year,sunrise,sunset,moonphase,moon_svis,moonrise,moonset,moonmeridian from astro where location=$dblocation and month=$targetmonth and year=$targetyear");
	$rq->execute();
	$ar2=$rq->fetchall_arrayref;
	$rq->finish();
}

print "Content-type: text/html\n\n";
print <<TOP;
<HTML>
<HEAD>
<TITLE>Fishing Schiz</TITLE>
<LINK REL="SHORTCUT ICON" HREF="favicon.ico">
<STYLE>
* {
        font-family: arial,helvetica,sans-serif;
}

tr.good {
        background: #a0a0f0;
}
tr.excellent {
        background: #f0a0f0;
}

tr.tr1 {
	background: #e0e0e0;
}
tr.tr2 {
	background: #f0f0f0;
}

tr.tr100 {
	background: #a0a0ff;
	font-weight: bold;
}

td {
        font-size: 8pt;
        text-align: center;
}

td.quality {
	text-align: left;



th {
        background: #d0d0d0;
        font-weight: bold;
        padding: 2px;
        border-style: solid;
        border-width: 2px 2px 2px 2px;
        border-color: #ffffff;
}

</STYLE>
</HEAD>
<BODY>
<TABLE cellspacing=1>
TOP

print "<TR><FORM METHOD=post><TD colspan=10><SELECT name=targetmonth>\n";
$m=1;
foreach $mth (@months) {
	if ($m == $targetmonth) {
		print "<OPTION VALUE=$m selected>$mth</OPTION>\n";
	} else {
		print "<OPTION VALUE=$m>$mth</OPTION>\n";
	}
	$m++;
}
print "</SELECT><SELECT name=targetyear>\n";
(undef,undef,undef,undef,undef,$currentyear,undef,undef,undef)=localtime(time);
$currentyear=1900+$currentyear;
for ($i=$currentyear; $i<$currentyear+2; $i++) {
	if ($i == $targetyear) {
		print "<OPTION VALUE=$i SELECTED>$i</OPTION>\n";
	} else {
		print "<OPTION VALUE=$i>$i</OPTION>\n";
	}
}		
print "</SELECT>\n";

print "<SELECT name=algo>\n";
foreach $alg (@algos) {
	if ($alg eq $algo) {
		print "<OPTION VALUE=$alg selected>$alg</OPTION>\n";
	} else {
		print "<OPTION VALUE=$alg>$alg</OPTION>\n";
	}
}
print "</SELECT>\n";

print "<SELECT name=location>\n";
foreach $loc (@locations) {
	if ($loc eq $location) {
		print "<OPTION VALUE=\"$loc\" selected>$loc</OPTION>\n";
	} else {
		print "<OPTION VALUE=\"$loc\">$loc</OPTION>\n";
	}
}
print "</SELECT>\n";

print "<INPUT TYPE=submit value=Display></TD></FORM></TR>\n";

##Old One
#print "<TR><TH>Date</TH><TH>Sunrise</TH><TH>Sunset</TH><TH>Moon Phase (Surface Visibility)</TH><TH>High Tide Time</TH><TH>Mean Tide Size</TH><TH></TH><TH></TH><TH>Moon Events</TH></TR>\n";

print "<TR><TH>Date</TH><TH>Sunrise</TH><TH>Sunset</TH><TH>Moon Rise</TH><TH>Moon Set</TH><TH>Moon Meridian</TH><TH>Phase</TH><TH colspan=2>Tide Info</TH><TH>Quality</TH><TH>Foo</TH></TR>\n";
$tog=1;
foreach $ar (@$ar2) {
	($day,$month,$year,$sunrise,$sunset,$moonphase,$moonvis,$moonrise,$moonset,$moonmeridian)=@$ar;
#	$dblocation=$db->quote($location);
	$rq=$db->prepare("select time,meansize from tide where location=$dblocation and day=$day and month=$month and year=$year and meansize > 0 order by time");
	$tidelines=$rq->execute();
	$br=$rq->fetchall_arrayref;
	$rq->finish();
	undef @tides; undef @result;
	foreach $brf (@$br) {
		my ($time,$size)=@$brf;
		if ($algo eq "fm_ht_sssr") {
			$res=algo_fm_ht_sssr($sunrise,$sunset,$time,$moonvis);
		} elsif ($algo eq "nm_ht_sssr") {
			$res=algo_nm_ht_sssr($sunrise,$sunset,$time,$moonvis);
		} elsif ($algo eq "algo_mt_sssr_ht_nmfm") {
			($res,$scoresummary)=algo_mt_sssr_ht_nmfm($sunrise,$sunset,$time,$moonvis,$moonrise,$moonset,$moonmeridian);
		}

		push @fields,"$day/$month/$year";
		push @gtidetime,$time;
		print STDERR "$time - ";
		push @gmoonvis,int($moonvis*14.4);
		push @gsunrise,$sunrise;
		push @gsunset,$sunset;
		push @gmoonrise,$moonrise;
		push @gmoonset,$moonset;
		push @gmoonmeridian,$moonmeridian;

		$time=secstotime($time);
		print STDERR "$time\n";
		push @tides,"<TD>$time</TD><TD>$size m</TD>";
		push @result, "<TD class=quality title=\"$scoresummary\">$res</TD>";
	}


	$sunrise=secstotime($sunrise);
	$sunset=secstotime($sunset);
	$moonrise=secstotime($moonrise);
	$moonset=secstotime($moonset);
	$moonmeridian=secstotime($moonmeridian);

	if (($day == $myday) and ($month == $mymonth) && ($year == $myyear)) {
		$ptog=$tog;
		$tog=100;
	}

	print "<TR class=tr$tog><TD rowspan=$tidelines>$day/$month/$year</TD><TD rowspan=$tidelines>$sunrise</TD><TD rowspan=$tidelines>$sunset</TD><TD rowspan=$tidelines>$moonrise</TD><TD rowspan=$tidelines>$moonset</TD><TD rowspan=$tidelines>$moonmeridian</TD><TD rowspan=$tidelines>$moonphase ($moonvis%)</TD>@tides[0]@result[0]<TD>Foo</TD></TR>\n";

	if ($tidelines > 1) {
		for ($i=2; $i<= $tidelines; $i++) {
		print "<TR class=tr$tog>@tides[$i-1]@result[$i-1]<TD>Foo</TD></TR>\n";
		}	
	}

	if ($tog == 100) {
		$tog=$ptog;
	}

	if ($tog == 1) {
		$tog=2;
	} else {
		$tog=1;
	} 
}

$graph=setupGraph(@fields);

$graph -> add_data({'data' => \@gmoonvis,
                'title' => 'Moon Surface Visibility'});
$graph -> add_data({'data' => \@gsunrise,
                'title' => 'Sunrise'});
$graph -> add_data({'data' => \@gsunset,
                'title' => 'Sunset'});
$graph -> add_data({'data' => \@gmoonrise,
                'title' => 'Moonrise'});
$graph -> add_data({'data' => \@gmoonset,
                'title' => 'Moonset'});
$graph -> add_data({'data' => \@gmoonmeridian,
                'title' => 'MoonMeridian'});
$graph -> add_data({'data' => \@gtidetime,
                'title' => 'High Tide Time'});

open F,">/var/www/fishing/svg.svgz" or die "Cannot write file: $!";
print F $graph->burn();
close F;




print <<BOTTY;
</TABLE>
<object data="svg.svgz" type="image/vnd.adobe.svg+xml"
        width="1000" height="500">
    <embed src="svg.svgz" type="image/vnd.adobe.svg+xml"
            width="1100" height="500" />
</object>
</BODY>
</HTML>
BOTTY


exit(0);

sub stripTable {
        my ($data)=@_;
        my @data=split('\n',$data);
        my $intable=0;

	$updaterrd=0;
        foreach $line (@data) {
                if ((index($line,"Tide Height (m)")>0) && ($intable == 0) ) {
#                        print "Found start with $line\n";
                        $intable=1;
                        next;
                }
                if ( (index($line,"table")>0) && ($intable == 1) ) {
#                        print "Found end with $line\n";
                        $intable=0;
                        last;
                }

                if ($intable == 1) {
                        if (index($line,"red")>0) {
                                $dst=1;
                        } else {
                                $dst=0;
                        }
                        $line=~ s/\<\/td//g;
                        (undef,undef,$date,$undef,$time,undef,$size)=split(">",$line);

			($yy,$mm,$dd)=split('\/',$date);			

			($h,$m)=split(':',$time);
			$dbtime=($h*60)+$m;

			print STDERR "Placing values into db:  $dblocation,$dd,$mm,$yy,$dst,$dbtime,$size\n";
			$db->do("insert into tide (location,day,month,year,dst,time,meansize) values ($dblocation,$dd,$mm,$yy,$dst,$dbtime,$size)");


                }

        }

}



