#!/usr/bin/perl -w

use strict;
use LWP::UserAgent;
use HTTP::Request;
use Date::Calc qw{ Today Today_and_Now Delta_YMDHMS Add_Delta_YMDHMS System_Clock };
use Astro::Sunrise;
use Image::Magick;
use Data::Dumper;

use constant DEBUG => 1;
use constant PAUSE => 10;
use constant BASE_DIR => '/home/fliptop/tv-ip501p/';

open LOG, '>>/tmp/grab_pic_tv-ip501p.log' or die "can't open log file: $!";
print LOG "\n------------------------------------------\n" if DEBUG;
printf LOG "Today is %s/%02d/%02d\n", Today if DEBUG;
print LOG "calculating 45 minutes before sunrise and 2 hours after sunset: " if DEBUG;

my @time = System_Clock;	# dst is last value in list
my ($sunrise, $sunset) = sunrise(Today, xx.xx, yy.yy, 5, $time[8]);
my ($srh, $srm) = split /:/, $sunrise;
my ($ssh, $ssm) = split /:/, $sunset;

my @sr_adjusted = Add_Delta_YMDHMS(Today, $srh, $srm, 0, 0, 0, 0, 0, -45, 0);
my @ss_adjusted = Add_Delta_YMDHMS(Today, $ssh, $ssm, 0, 0, 0, 0, 2, 00, 0);

printf LOG "%s:%s %s:%s\n", $sr_adjusted[3], $sr_adjusted[4], $ss_adjusted[3], $ss_adjusted[4] if DEBUG;

my @start_time = ($sr_adjusted[3], $sr_adjusted[4], '00');
my @end_time = ($ss_adjusted[3], $ss_adjusted[4], '00');

my $uri = 'http://username:password@192.168.1.246/IMAGE.JPG';
my $ua = LWP::UserAgent->new;
$ua->agent("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.13) Gecko/2009080317 Fedora/3.0.13-1.fc10 Firefox/3.0.13");

my $im = Image::Magick->new();

for (0..86400/PAUSE) {

  my @Today = Today;
  my @Today_and_Now = Today_and_Now;

  # create dir if it doesn't exist
  my $dir = sprintf "%s%s/%02d/%02d", BASE_DIR, @Today;

  unless (-e $dir) {
    printf LOG "creating base directory %s\n", $dir if DEBUG;

    my $resp = qx{ /bin/mkdir -p $dir };

    if ($resp) {
      printf LOG "unable to create image dir: %s\n", $resp;
      die;
    }
  }

  if ( &_take_pic(\@Today, \@Today_and_Now) ) {

    my $not_jpeg = 1;

    my $res = $ua->request(HTTP::Request->new(GET => $uri));
    my $status = $res->status_line;

    unless ($status eq '200 OK' || $status eq '302 Found') {
      printf LOG "unable to request image, status code is: %s\n", $status if DEBUG;
    }

    while ($not_jpeg) {
      my $headers = $res->{_headers};
      my $ct = $headers->{'content-type'};

      if ($ct eq 'text/plain') {
        print LOG 'text/plain (no image) result: ', Dumper($res), "\n" if DEBUG;
        sleep 2;


        # request it again
        $res = $ua->request(HTTP::Request->new(GET => $uri));
        $status = $res->status_line;

        unless ($status eq '200 OK' || $status eq '302 Found') {
          printf LOG "unable to request image, status code is: %s", $status, "\n" if DEBUG;
        }
      }
      elsif ($ct eq 'image/jpeg') {
        print LOG 'image/jpge found: ', $headers->{'client-date'}, "\n" if DEBUG;
        $not_jpeg = 0;
      }
      else {
        print LOG "unknown content-type: ", $ct, "\n" if DEBUG;
        sleep 2;

        # request it again
        $res = $ua->request(HTTP::Request->new(GET => $uri));
        $status = $res->status_line;

        unless ($status eq '200 OK' || $status eq '302 Found') {
          printf LOG "unable to request image, status code is: %s", $status, "\n" if DEBUG;
        }
      }
    }
    my $content = $res->{_content};
    my $filename = sprintf "%s/%s.jpg", $dir, time;

    printf LOG "writing image %s\n", $filename if DEBUG;

    open BIN, ">$filename" or die "can't open binary output file: $!";
    binmode BIN;
    print BIN $content;
    close BIN;

    print LOG "image written\n" if DEBUG;
    print LOG "annotating date\n" if DEBUG;

    my $x = $im->Read($filename);
    print LOG "$x: $filename\n" if $x && DEBUG;

    $x = $im->Annotate(
      text       => sprintf("%s/%02d/%02d %02d:%02d:%02d", @Today_and_Now),
      font       => '/usr/share/fonts/dejavu/DejaVuSans-ExtraLight.ttf',
      pointsize  => 12,
      stroke     => 'white',
      undercolor => 'blue',
      fill       => 'red',
      x          => 510,
      y          => 465
    );
    print LOG "$x: $filename\n" if $x && DEBUG;

    $x = $im->Write($filename);
    print LOG "$x: $filename\n" if $x && DEBUG;

    @{$im} = ();	# clear the buffer
  }

  sleep PAUSE;
}

close LOG;

exit();

sub _take_pic {
  my ($todayref, $today_and_nowref) = @_;
  my @Today = @{ $todayref };
  my @Today_and_Now = @{ $today_and_nowref };

  my @after_start = Delta_YMDHMS(@Today, @start_time, @Today_and_Now);
  my @before_end = Delta_YMDHMS(@Today_and_Now, @Today, @end_time);

  # time is array elements 3, 4 and 5
  return 0 if $after_start[3] < 0 || $after_start[4] < 0 || $after_start[5] < 0;
  return 0 if $before_end[3] < 0 || $before_end[4] < 0 || $before_end[5] < 0;

  return 1;
}
