#!/usr/bin/perl
use Time::Local;
use Text::ParseWords;
require "plans_config.pl";
require "plans_lib.pl";


sub adjust_event {
# DO NOT MODIFY! This function is a stub.  Modify the function in plans_import_custom.pl instead
  my ($event_ref) = @_;
  return $event_ref;
}

# if you want to customize this script, feel free.
# You can do so in a non-break-compatibility way by modifying the functions in the file below.
if (-e "plans_import_custom.pl") {
  require "plans_import_custom.pl";
}


&load_calendars();
&load_events("all");

$rightnow=time();

my $import_file=$ARGV[0];

if ($import_file eq "") {
  die("Error!  No import file specified.\n");
}

# right now, outlook is the only import type supported
my $data_type="outlook_csv";



my @events_lines;
print "\nThis utility imports data from various formats into Plans.\n";

if ($data_type eq "outlook_csv") {
  print "Looking for existing calendars...\n";
  my $import_calendar=0;
  if (scalar keys %calendars == 0) {
    die("Error!  No calendars found!\n");
  } elsif (scalar keys %calendars > 1) {
    print "Choose which calendar to attach the imported events to:\n";
    foreach $cal_id (sort {$a <=> $b} keys %calendars) {
      print "$cal_id - $calendars{$cal_id}{title}\n";
    }
    $import_calendar = <STDIN>;
    chomp $import_calendar;
    
    if (!(defined $calendars{$import_calendar})) {
      die("Error!  Invalid calendar chosen!\n");
    }
  }
  
  open (FH, "$import_file") || die( "unable to open file $import_file\n");
  flock FH,2;
  my @import_lines=<FH>;
  close FH;
  
  shift @import_lines;  # don't care about the first line (the field defs)
  
  my $import_string= join("\n", @import_lines);
  $import_string =~ s/\r+//g;             # get rid of carraige return characters
  $import_string =~ s/\n+/\n/g;           # get rid of extra newlines
  $import_string =~ s/,"\n",/,,/g;        # properly escape fields containing only carraige returns:  ,"\n",
  $import_string =~ s/([^,])""([^,])/$1\\"$2/g;           # properly escape " characters inside fields
  
  $import_string =~ s/([^"])\n+/$1\\n/g;  # handle records that span multiple lines.  
                                          # The MS programmer who decided records 
                                          # should span multiple lines owes the 
                                          # world an apology.
  

  
  @import_lines = split("\n", $import_string);
  
  my @new_event_ids;
  
  $index = 0;
  foreach $line (@import_lines) {
    my @values = &quotewords(",", 0 , $line);
    my $event_title = $values[0];
    my $event_details = $values[16];
    my $start_date = $values[1];
    my $start_time = lc $values[2];
    my $end_date = $values[3];
    my $end_time = lc $values[4];
    my $all_day_event = lc $values[5];
    my $event_start_timestamp;
    my $event_end_timestamp;
    my $event_days;

    print "line $index, title $event_title start date: $start_date\n";
    print "$line\n";
    
    my ($start_month, $start_mday, $start_year) = split("/", $start_date);
    $start_month--;
    my ($start_time, $start_ampm) = split(" ", $start_time);
    my ($start_hour, $start_minute, $start_second) = split(":", $start_time);
    
    if ($start_ampm =~ /pm/ && $start_hour < 12) {$start_hour +=12;}
    
    if ($all_day_event eq "true" || $all_day_event eq "") {
      $event_start_timestamp = timegm(0,0,0,$start_mday,$start_month,$start_year);
    } else { # event times might not be entirely accurate.
      $event_start_timestamp = timegm($start_second,$start_minute,$start_hour,$start_mday,$start_month,$start_year);
    }
    
    $end_date = $start_date if ($end_date eq "");
    
    my ($end_month, $end_mday, $end_year) = split("/", $end_date);
    print "end_date: $end_date\n";
    $end_month--;
    my ($end_time, $end_ampm) = split(" ", $end_time);
    my ($end_hour, $end_minute, $end_second) = split(":", $end_time);
    
    if ($end_ampm =~ /pm/ && $end_hour < 12) {$end_hour +=12;}
    
    if ($all_day_event eq "true" || $all_day_event eq "") {
      $event_end_timestamp = timegm(59,59,23,$end_mday,$end_month,$end_year);
      $event_end_timestamp = $event_end_timestamp - 86400;
    } else {# event times might not be entirely accurate.
      $event_end_timestamp = timegm($end_second,$end_minute,$end_hour,$end_mday,$end_month,$end_year);
    }
    
    $event_days = &roundup((($event_end_timestamp-$event_start_timestamp)/86400));

    #print "$index: $start_timestamp $end_timestamp\n";

    $max_event_id += 1;
    push @new_event_ids, $max_event_id;

    my @evt_cal_ids = ($import_calendar);
    
    $event_start_timestamp -= $calendars{$evt_cal_ids[0]}{gmtime_diff} * 3600;
    $event_end_timestamp -= $calendars{$evt_cal_ids[0]}{gmtime_diff} * 3600;

    $events{$max_event_id} = &adjust_event({id => $max_event_id, 
                              cal_ids => \@evt_cal_ids, 
                              start => $event_start_timestamp, 
                              end => $event_end_timestamp, 
                              days => $event_days,
                              title => $event_title,
                              details => $event_details,
                              icon => "",
                              bgcolor => "#ffffff",
                              unit_number => "",
                              update_timestamp => $rightnow},\@values);

    $index++;
  }
  
  print "Conversion successful! (no formatting or syntax errors)\n";
  print "Adding $index new events to plans\n";
  
  foreach $event_id (@new_event_ids) {
    &add_event($event_id);
  }
}


sub round {
  my ($float) = shift;
  return int($float + .5);
}

sub roundup {
  my ($float) = shift;
  return int($float + 1);
}
