#!/usr/bin/perl
use HTML::TreeBuilder;
use HTML::ElementTable;
use DateTime::Format::ICal;
use Data::ICal::Entry::Event;
use Data::ICal;

@start = ('7:30', '8:15', '9:15', '10:15', '11:00', '12:00', '12:45', '13:45', '14:30', '15:30', '16:15', '17:15', '18:00', '19:00');
@intervals = ('29.9.2008', '19.12.2008', '5.1.2009', '16.1.2009');
$tree=HTML::TreeBuilder->new_from_file('rozvrh.html'); 
$tab=HTML::ElementTable->new_from_tree($tree->look_down("_tag", "table", "class", "timetable"));
$calendar = Data::ICal->new();

@index = (3);
for($i = 3; scalar @index < 5; $i++){
	next unless defined $tab->cell($i, 0)->attr('rowspan');
	push @index, $index[scalar @index - 1] + $tab->cell($i, 0)->attr('rowspan');
}

for($interval = 0; $interval < scalar @intervals; $interval += 2){
	($day, $month, $year) = $intervals[$interval] =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)$/;
	$d_s = DateTime->new( 'year' => $year, 'month' => $month, 'day' => $day, 'hour'=>4);
	($day, $month, $year) = ($intervals[$interval + 1] =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)$/);
	$d_e = DateTime->new( 'year' => $year, 'month' => $month, 'day' => $day, 'hour'=>6);
	for(;$d_s->compare($d_e) != 1; $d_s->add(hours=>24)){
		$wd = $index[$d_s->dow-1] or next;
		for my $k (0 .. $tab->cell($wd, 0)->attr('rowspan') - 1){
			for($j = 0; $j < 15; $j += $delka){
				$delka = $tab->cell($wd+$k, 1+$j)->attr('colspan');
				$_ = $tab->cell($wd+$k, 1+$j)->attr('class');
				if(defined and (/^cviceni$/ or /^prednaska$/)){
					my $event = Data::ICal::Entry::Event->new();
					my $nd = $d_s->clone();
					($h,$m)=$start[$j]=~/^([0-9]+):([0-9]+)$/;
					$nd->set(hour=>$h,minute=>$m); 
					$event->add_properties(summary =>$tab->cell($wd+$k, 1+$j)->as_trimmed_text(), dtstart=>DateTime::Format::ICal->format_datetime($nd));
					$nd->add(minutes=>$delka*45);
					$event->add_properties(dtend=>DateTime::Format::ICal->format_datetime($nd));
					$calendar->add_entry($event);
				};
			}
		}
	}
}
print $calendar->as_string;
