#!/usr/bin/perl

# By Mathias Moe (mathias@jpg.no) for Fr. James Smith, march 2019

use Data::ICal;
# use Data::ICal::Entry::Event;
use DateTime;
use DateTime::Format::ICal;
use JSON;

# Set outfile here
my $outfile = "/home/apps1/htdocs/mathias/CalTest/jms.ics";

# Instanciate the calendar
my $calendar = Data::ICal->new("JMS");

# Data source
my $source = `curl -L "http://www.rotundasoftware.com/ministry/FSSPATL/schedules/?pointer=last"`;

# Remove anything befor this
$source =~ s/^.*window.Baseline.bootstrapData =//s;

# Remove anything after this:
$source =~ s/^(.*?)\;window\.Baseline.*$/$1/s;


my $calendardata = decode_json($source);

my @masses = @{$calendardata->{ms}};

foreach $mass (@masses) {
	 print "$mass->{dateTime}: $mass->{name}\n";

	# Date-time is ALMOST ISO-8601
	my $datetime = $mass->{dateTime};
	$datetime =~ m/(\d{4})-(\d{2})-(\d{2})\s(\d{2})\:(\d{2})\:(\d{2})/;
	$dt = DateTime->new(
		year       => $1,
		month      => $2,
		day        => $3,
		hour       => $4,
		minute     => $5,
		second     => $6,
		nanosecond => 0
#		time_zone  => 'America/New_York'
		);

	$end = DateTime->new(
		year       => $1,
		month      => $2,
		day        => $3,
		hour       => $4,
		minute     => $5,
		second     => $6,
		nanosecond => 0
#		time_zone  => 'America/New_York'
		);


	# If name is set, use this else use label	
	my $summary = (($mass->{name} =~ m/\w/) ? $mass->{name} : $mass->{label});

	# Add hours and minutes to get end
	$end->add( hours => $mass->{duration}->{hours}, minutes => $mass->{duration}->{minutes} );

	
	my $ts = DateTime->now;

	my $vevent = Data::ICal::Entry::Event->new();

    $vevent->add_properties(
        summary => $summary,
        description => "",
        # Dat*e*::ICal is not a typo here
        dtstart   => DateTime::Format::ICal->format_datetime($dt),
        dtend     => DateTime::Format::ICal->format_datetime($end),
        dtstamp => DateTime::Format::ICal->format_datetime($ts),
        uid        => $mass->{_id}
        );


	$calendar->add_entry($vevent);
	}


open (FH, '>', "$outfile") or die $!;
print FH $calendar->as_string;
close FH;
