auto
 ?÷     # $Id$
package iCal::Parser;
use strict;

our $VERSION='1.21';

our @ISA = qw (Exporter);

use DateTime::Format::ICal;
use DateTime::TimeZone;
use Text::vFile::asData;
use File::Basename;
use IO::File;
use IO::String;

# mapping of ical entries to datatypes
our %TYPES=(dates=>{DTSTAMP=>1,DTSTART=>1,DTEND=>1,COMPLETED=>1,
                    'RECURRENCE-ID'=>1,EXDATE=>1,DUE=>1,
                    'LAST-MODIFIED'=>1,
                },
            durations=>{DURATION=>1},
            arrays=>{EXDATE=>1,ATTENDEE=>1},
            hash=>{'ATTENDEE'=>1, ORGANIZER=>1},
        );

our %defaults=(debug=>0,span=>undef,start=>undef,end=>undef,months=>60,tz=>'local');

our $dfmt=DateTime::Format::ICal->new;
our $parser=Text::vFile::asData->new;
sub new {
    my ($class, %params) = @_;

    my $self=bless {%defaults, %params,
                    ical=>{cals=>[],events=>{},todos=>[]},
                    _today=>DateTime->now,_calid=>0,
                }, $class;
    #set range, allow passed in dates as DateTimes or strings
    my $start=$params{start}||DateTime->now->truncate(to=>'year');
    $start=$dfmt->parse_datetime($start) unless ref $start;
    my $end=$params{end}||$start->clone->add(months=>$self->{months});
    $end=$dfmt->parse_datetime($end) unless ref $end;
    $self->{span}||=DateTime::Span->new(start=>$start, end=>$end);

    $self->{tz}=DateTime::TimeZone->new(name=>$self->{tz})
        unless ref $self->{tz};

    return ($self);
}
sub parse {
    my $self=shift;

    foreach my $file (@_) {
        my $fh=ref $file ? $file
            : IO::File->new($file,'r') || die "Can\'t open $file, $!";
        my $data=$parser->parse($fh);
        undef $fh;

        $self->VCALENDAR($data->{objects}[0],$file);
        $self->add_objects($data->{objects}[0]);
        $self->update_recurrences;
    }
    return $self->{ical};
}
sub parse_files {
    return parse(@_);
}
sub parse_strings {
    my $self=shift;
    return $self->parse((map { IO::String->new($_) } @_));
}
sub calendar {
    return shift->{ical};
}
sub VCALENDAR {
    my($self,$cal,$file)=@_;

    my %props=();
    $self->{recurrences}=[];
    $self->map_properties(\%props,$cal);
    $props{'X-WR-TIMEZONE'}||=$self->{tz}->name;
    $props{index}=++$self->{_calid};
    $props{'X-WR-RELCALID'}||=$self->{_calid};
    $props{'X-WR-CALNAME'}||= ref $file
        ? "Calendar $self->{_calid}" : fileparse($file,qr{\.\w+});

    push @{$self->{ical}{cals}},\%props;
}
sub VTODO {
    my($self,$todo)=@_;
    return if $self->{no_todos};

    my $t={idref=>$self->_cur_calid};
    $self->map_properties($t,$todo);
    $t->{PRIORITY}||=99;

    $self->add_objects($todo,$t);
    push @{ $self->{ical}{todos} }, $t;
}
sub VEVENT {
    my($self,$event)=@_;
    return if $self->{no_events};

    my %e=(idref=>$self->_cur_calid);

    $self->map_properties(\%e,$event);
    $self->add_objects($event,\%e);

    my $start=$e{DTSTART};
    return if $start > $self->{span}->end;

    warn "Event: @e{qw(UID DTSTART SUMMARY)}\n"
        if $self->{debug};

    # stolen from Text::vFile::asData example
    $e{allday}=1 if (_param($event,'DTSTART','VALUE')||'') eq 'DATE';

    #is it a rule that an event must contain either a duration or end?
    # answer: no, it's not (cpan bug #25232)
    my $end=$e{DTEND};
    my $duration=$end ? $end-$start : delete $e{DURATION};
    $duration ||= DateTime::Duration->new(days=> $e{allday} ? 1 : 0);
    $e{DTEND}||=$start+$duration;
    $e{hours}=_hours($duration) unless $e{allday};

    #build recurrence sets
    my $set;
    if (my $rid=$e{'RECURRENCE-ID'}) {
        return if $start < $self->{span}->start;
        push @{ $self->{recurrences} }, \%e;
        return;
    }
    if (my $recur=delete $e{RRULE}) {
        $set=$dfmt->parse_recurrence(recurrence=>$recur, dtstart=>$start,
                                     #cap infinite repeats
                                     until =>$self->{span}->end);
    } elsif ($end) {
        # non-rrule event possibly spanning multiple days,
        # expand into multiple events
        if (!$e{al