#!/usr/bin/perl

use strict;
use warnings;

use Text::CSV;
use Data::Dumper;

print qx{rm -rf /tmp/kmls};
mkdir "/tmp/kmls";

sub stuffout {
  my $sid = shift;

  open(my $kmlfh, ">>", "/tmp/kmls/$sid.kml" );

  print $kmlfh qq{<?xml version="1.0" encoding="UTF-8"?>
<!-- Mockup for historic sea ice display. Data is bogus. Created 13 Nov 2011 by J. Davis jldavis94\@gmail.com -->
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <Style id="noIce">
      <IconStyle>
        <scale>.5</scale>
        <Icon>
          <href>http://users.digitalkingdom.org/~jdavis/sjsu_slis/LIBR220-st/images/lake.png</href>
        </Icon>
      </IconStyle>
    </Style>
    <Style id="ice">
      <IconStyle>
        <scale>.5</scale>
        <Icon>
          <href>http://users.digitalkingdom.org/~jdavis/sjsu_slis/LIBR220-st/images/snowy-2.png</href>
        </Icon>
      </IconStyle>
    </Style>
    <LookAt>
      <longitude>-170</longitude>
      <latitude>63</latitude>
      <altitude>2000000</altitude>
    </LookAt>
    };

    # print "at under".Dumper(\@_)."\n";
  foreach my $segment (@_) {
    my ($icecov, $sid, $year, $month, $day, $lat, $long, $style) = @{$segment};

    print $kmlfh qq{
    <Placemark>
      <name>$sid $day $month $year</name>
      <styleUrl>$style</styleUrl>
      <Point>
        <coordinates>$long,$lat,0</coordinates>
      </Point>
    </Placemark>
    };
  }

  print $kmlfh qq{
  </Document>
</kml>    
  };

  close($kmlfh);
}

#my @rows;
my $csv = Text::CSV->new ({ binary => 1, sep_char => "\t" }) or die "Cannot use CSV: ".Text::CSV_XS->error_diag ();
open my $fh, "<:encoding(utf8)", "/tmp/WhaleshipDataForWeb.txt" or die "test.csv: $!";

my %ships;

while (my $row = $csv->getline ($fh)) {
  #print Dumper(\$row);
  #$row->[2] =~ m/pattern/ or next; # 3rd field should match
  #push @rows, $row;
  my $icecov = $row->[8];
  my $sid = $row->[0];
  my $year = $row->[2];
  my $month = $row->[3];
  my $day = $row->[4];
  my $lat = $row->[5];
  my $long = $row->[6];
  my $e_w = $row->[7];
  #print "ic: $icecov\n";

  # string compare so no coercion
  if( $icecov eq '0' ) {
    push @{$ships{$sid}}, [$icecov, $sid, $year, $month, $day, $lat, $long, "#noIce"];
  }
  if( $icecov eq '1' ) {
    push @{$ships{$sid}}, [$icecov, $sid, $year, $month, $day, $lat, $long, "#ice"];
  }
}
$csv->eof or $csv->error_diag ();
close $fh;

# print "ships: ".Dumper(\%ships)."\n";
foreach my $sid (keys %ships) {
  stuffout($sid, @{$ships{$sid}});
}

print qx{rm /tmp/kmls.zip};
print qx{zip -r /tmp/kmls.zip /tmp/kmls/};
