#!perl
use warnings; use strict;
use Test::More tests => 8;
use Test::Exception;

use lib '.';
use t::Elive;

BEGIN {
    use_ok( 'Elive' );
    use_ok( 'Elive::Entity::Meeting' );
};

my $class = 'Elive::Entity::Meeting' ;

SKIP: {

    my %result = t::Elive->auth();
    my $auth = $result{auth};

    skip ($result{reason} || 'unable to find test connection',
	6)
	unless $auth;

    Elive->connect(@$auth);

    my %meeting_str_data = (
	name => 'test meeting, generated by t/21-soap-meeting.t',
	password => 'test', # what else?
    );

    my %meeting_int_data = (
	facilitatorId => Elive->login->userId,
	start => time() .'000',
	end => (time()+900) . '000',
	recurrenceCount => 3,
	recurrenceDays => 7,
	
    );

    my @meetings = ($class->insert({%meeting_int_data, %meeting_str_data}));

    ok(@meetings == 3, 'got three meeting occurences')
	or exit;

    foreach (@meetings) {
	isa_ok($_, $class, "meeting occurence");
    }

    my @start_times = map {substr($_->end, 0, -3)} @meetings;

    #
    # very approximate test on the dates being about a week apart.
    # The times could be out by over half an hour due to daylight 

    ok(a_week_between($start_times[0], $start_times[1]),
		       "meetings 1 & 2 separated by one week (approx)");

    ok(a_week_between($start_times[1], $start_times[2]),
       "meetings 2 & 3 separated by one week (approx)");

    foreach (@meetings) {
	$_->delete;
    }
}

sub a_week_between {
    my $start = shift;
    my $end = shift;

    #
    # A very rough test of times being about a week apart. Anything more
    # precise is going to require time-zone aware date/time calculations.
    #
    my $seconds_in_a_week = 7 * 24 * 60 * 60;
    #
    # just test that the dates are a week apart to within an
    # hour and a half, or so. This should accomodate daylight savings
    # adjustments of up to 1.5 hours.
    #
    my $delta = 1.6 * 60 * 60; # a little over 1.5 hours
    my $ok = abs ($end - $start - $seconds_in_a_week) < $delta;

    return $ok;
}

Elive->disconnect;
