use strict;
use warnings;
use POSIX;

require "graphMerge.pl";

#
# This function is from gatlas. Thanks for him
sub CDppToKMLTime
{
   # CDpp has the folling time format:
   # 00:00:00:000
   # HH:MM:SS:milisecond
   #
   # KML uses YYYY-MM-DDThh:mm:ss.sss
   my ($cdpp_time) = @_ ; 

   my $fake_date = "2010-01-01" ; 

   my ($h,$m,$s,$msec)=(0,0,0,0) ;

   # GE doesn't like to show anything less than 1 sec increments, so 
   # we will have to play with the time
   # we have increments of 200 ms in the logs so we'll multiply time by
   # 5 to view the results
   if ( $cdpp_time =~ /(.*):(.*):(.*):(.*)/ )
   {
      #print "Old cdpp_time $cdpp_time\n" ; 
      $h = $1 ; 
      $m = $2 ; 
      $s = $3 ; 
      $msec = $4 ;  

      # bring it all the way down to the number of ms we have
      $m = $m + 60 * $h ; 
      $s = $s + 60 * $m ;
      $msec = $msec + $s*1000 ; 

      #multiply by 5
      $msec = $msec * 5000000 ;

      #build up the original time again
      $s = $msec / 1000 ; 

      $m =  floor($s / 60 ) ; 
      $s =  $s % 60 ; 

      $h =  floor($m / 60 ) ; 
      $m =  $m % 60 ; 

    #  $cdpp_time = sprintf("%02d:%02d:%02d:000",$h,$m,$s);
      #print "New cdpp_time $cdpp_time\n" ; 
   }
   else
   {
      die "Problem in " . __FILE__ ."-". __LINE__ . "\n" ; 
   }

   my $kml_time = $cdpp_time ; 

   # replace the ":" between seconds and ms with a "."
   $kml_time =~ s/(.*):(.*)/$1\.$2/ ; 

   $kml_time = $fake_date . "T" .  $kml_time ; 
}


sub analyze_events
{
  my ($log_file,$events_ref) = @_;
  
 
  open(IN, "<$log_file")  or die("Cannot open file $log_file for reading\n");
  
 # print "$log_file \n ";
 
  my $event_element = "";
  my $event_time  = "" ;
  my $event_row  = 0  ;
  my $event_column  = 0  ; 
  my $event_layer  = 0  ; 
  my $event_value = 0  ; 

# sleep;
  
  while ( my $line_in = <IN> )
  {
  #Mensaje Y / 00:00:38:400 / libertador_b1(0,6)(1478) / out /      1.00000 para libertador_b1(1471)
  #Mensaje Y / 00:00:00:200 / urbangrowth(0,6,0)(15) / out /      6.00000 para urbangrowth(02)
        if ( $line_in =~ /Mensaje Y \/\s*(\S*)\s*\/ (.*)\((\d*),(\d*),(\d*)\).*\/.*\/\D*([0-9\.]*).*/ )
        {
           $event_element = lc($2) ;
           $event_time = $1;
           $event_row = $3 ; 
           $event_row += 0  ; 
           $event_column = $4 ; 
           $event_column += 0 ; 
           $event_layer = $5 ; 
           $event_layer += 0 ;
           $event_value = $6 ; 
           $event_value +=0 ; #quickly strip n.00000 to n
    #       print  "[$1,($2),$3,$4,$5,$event_value]". $line_in . "\n" ; 

           $events_ref->{$event_layer}{$event_time}{$event_row}{$event_column} = $event_value ; 
        }
        elsif( $line_in =~ /Mensaje Y \/\s*(\S*)\s*\/ (.*)\((\d*),(\d*)\).*\/.*\/\D*([0-9\.]*).*/ )
        {
           $event_element = lc($2) ;
           $event_time = $1;
           $event_row = $3 ; 
           $event_row += 0  ; 
           $event_column = $4 ; 
           $event_column += 0 ; 
           $event_value = $5 ; 
           $event_value +=0 ; #quickly strip n.00000 to n
    #       print  "[$1,($2),$3,$4,$event_value]". $line_in . "\n"  ; 

           $events_ref->{$event_layer}{$event_time}{$event_row}{$event_column} = $event_value ; 
        }
        
     }

  close(IN);

}


sub initiate_kml
{
   my ($kml_text_ref,$state_style_array_ref,$index_map_state_ref,$outline)=@_;
   
   
   $$kml_text_ref .= <<KMLEND;
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
  <name>visualization</name>
  <open>0</open>
KMLEND

   my $count_style = $#{$index_map_state_ref}+1;
 #  print $count_style;
   for(my $idx=0; $idx < $count_style; $idx++)
   {
     $$kml_text_ref .= <<KMLEND; 
     <Style id="$state_style_array_ref->[$index_map_state_ref->[$idx]][0]">
       <PolyStyle>
         <color>$state_style_array_ref->[$index_map_state_ref->[$idx]][1]</color>
         <colorMode>normal</colorMode>
         <outline>$outline</outline> 
       </PolyStyle>
     </Style>    
     
KMLEND
    }
    
$$kml_text_ref .= <<KMLEN;
   <Style id="unchecked">
     <ListStyle>
      <listItemType>checkOffOnly</listItemType>
    </ListStyle>
    </Style>
KMLEN

   
}



sub end_kml
{
   my ($kml_text_ref)=@_;
   $$kml_text_ref .= <<KMLEND;
</Document>
</kml>
KMLEND

}

sub initiate_change_matrix
{
  my ($matrix_ref,$row_num,$column_num)=@_;
  
  for(my $idx_row=0;$idx_row<$row_num;$idx_row++)
  {
   for(my $idx_column=0;$idx_column<$column_num;$idx_column++)
   {
     $matrix_ref->[$idx_row][$idx_column] = "x";
   }
  }
  
}

sub body_kml
{
  my ($kml_text_ref, $cells_matrix_ref, $log_file, $state_style_array_ref,$index_map_state_ref,$geoinfo_array_ref) = @_;

  my @cells_matrix = @$cells_matrix_ref;
  my $cells_layer_num = @cells_matrix;
  my $cells_row_num = $#{$cells_matrix[0]} + 1;
  my $cells_column_num = $#{$cells_matrix[0][0]} + 1;
  
  # print $cells_layer_num . " " . $cells_row_num .  " " . $cells_column_num . " " . "\n";
  # sleep;
  # print "body_body \n";
  my @cells_matrix_merge;
  my @cells_merge_style_array;
  my @graph;
  my $visibility=1;
  my $style;
  my $time;
  my $kml_time;
  my %events;
  my @events_matrix_merge;
  my @events_merge_style_array;
  # we use this array to annotate the cell array
  my @events_matrix; 
  my $test_file="test.txt"; 
  open( TEST , ">$test_file" ) or die "Could not open $test_file for writing\n";
  
  
  #print "$log_file \n";
  analyze_events($log_file,\%events);
  
  my @layers     = sort keys (%events) ;
  my $events_layer_num = @layers;
  

  
  if($cells_layer_num!=$events_layer_num)
  {
    print "\t"."It is curios to find that the the layer num of cells isn't the same as the layer of events \n";
  }
  
  # generate the kml body 
  # we iterate every layer 
  for(my $idx_z=0; $idx_z < $cells_layer_num; $idx_z++)
  {
     @cells_matrix_merge=();
     @cells_merge_style_array=();
     @graph=();
     merge_cells(\@{$cells_matrix[$idx_z]},\@cells_matrix_merge,\@cells_merge_style_array);
     generate_graph(\@cells_matrix_merge, \@cells_merge_style_array,$geoinfo_array_ref,\@graph);
     

     
     if($idx_z!=0)
     {
        $visibility = 0;
     }
     ##folder starting
     $$kml_text_ref .= <<KMLEND;
    <Folder id="$idx_z layer">
    <name>$idx_z layer</name>
KMLEND
     

      ## folder body    
     $time = "00:00:00:000";
     $kml_time = CDppToKMLTime($time) ;    
      #we add the initial placemarks here
      for(my $idx_graph =0 ;  $idx_graph< $#graph+1; $idx_graph++)
      {
          $style=$state_style_array_ref->[$cells_merge_style_array[$idx_graph][0]][0];
            
          $$kml_text_ref  .= <<KMLEND;
                <Placemark>
          <name>graph-$idx_graph-$time</name>
          <styleUrl>#$style</styleUrl>
          <Polygon>
            <tessellate>1</tessellate>
            <outerBoundaryIs>
              <LinearRing>
                <coordinates>
KMLEND
               for(my $idx=0; $idx < (1+$#{$graph[$idx_graph]})/2 ; $idx++ )
               {
                   $$kml_text_ref  .= "$graph[$idx_graph][$idx * 2],$graph[$idx_graph][$idx * 2+1],0 \n";  
               }     
                        
             $$kml_text_ref  .= <<KMLEND;
                </coordinates>
              </LinearRing>
            </outerBoundaryIs>
          </Polygon>	
            <TimeStamp>
          <when>$kml_time</when>
        </TimeStamp>
        </Placemark>
KMLEND

      }
      
       #we add the following timing sequences
       foreach my $time ( sort keys %{$events{$idx_z}} )
       {
               @graph=();
               @events_matrix_merge=();
               @events_merge_style_array=();
               
               initiate_change_matrix(\@events_matrix,$cells_row_num,$cells_column_num );
      
               foreach my $row ( sort keys %{$events{$idx_z}{$time}} ) 
               {

                  foreach my $column ( sort keys %{$events{$idx_z}{$time}{$row}} )
                  {
              
                    $events_matrix[$row][$column]=$events{$idx_z}{$time}{$row}{$column};
              
                  }
                }
              merge_events_cells(\@events_matrix,\@events_matrix_merge,\@events_merge_style_array);
              generate_events_graph(\@events_matrix_merge, \@events_merge_style_array,$geoinfo_array_ref,\@graph);
      
              if($idx_z==1)
              {  
                print TEST "time is $time";
                foreach my $idx (0..$#events_merge_style_array)
                {
                  print TEST "@{$events_merge_style_array[$idx]} \n";
                }
              }
      
              
              $kml_time = CDppToKMLTime($time) ; 
              for(my $idx_graph =0 ;  $idx_graph< $#graph+1; $idx_graph++)
              {
                  $style=$state_style_array_ref->[$events_merge_style_array[$idx_graph][0]][0];
                    
                  $$kml_text_ref  .= <<KMLEND;
                        <Placemark>
                  <name>graph-$idx_z-$idx_graph-$time</name>
                  <styleUrl>#$style</styleUrl>
                  <Polygon>
                    <tessellate>1</tessellate>
                    <outerBoundaryIs>
                      <LinearRing>
                        <coordinates>
KMLEND
                         for(my $idx=0; $idx < (1+$#{$graph[$idx_graph]})/2 ; $idx++ )
                         {
                             $$kml_text_ref  .= "$graph[$idx_graph][$idx * 2],$graph[$idx_graph][$idx * 2+1],0 \n";  
                         }     
                                  
                       $$kml_text_ref  .= <<KMLEND;
                          </coordinates>
                        </LinearRing>
                      </outerBoundaryIs>
                    </Polygon>	
                      <TimeStamp>
                    <when>$kml_time</when>
                  </TimeStamp>
                  </Placemark>
KMLEND

                }
      
      
       }

     
     ## folder end 
     $$kml_text_ref .= "</Folder>\n" ;     
     
  }
}

1;