#!perl -T
use warnings; use strict;
use Test::More tests => 6;
use Test::Exception;
use Test::Builder;

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

use Elive;
use Elive::Entity::Session;
use Elive::Util;

use Carp; $SIG{__DIE__} = \&Carp::confess;

our $t = Test::Builder->new;
our $class = 'Elive::Entity::Session' ;

our $connection;

my %params;
@params{ $class->params} = undef;

ok(exists $params{until}
   && exists $params{repeatEvery}
   && exists $params{sundaySessionIndicator},
   'recurring session - sanity');

SKIP: {

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

    my $connection_class = $result{class};
    skip ($result{reason} || 'skipping live tests', 5)
	if $connection_class->isa('t::Elive::MockConnection');

    $connection = $connection_class->connect(@$auth);
    Elive->connection($connection);

    my $session_start = Elive::Util::next_quarter_hour();
    my $session_end = Elive::Util::next_quarter_hour($session_start);
    my $until = $session_end + (2*24 + 6) * 60 * 60; # advance 2 and a bit days

    my $start_msec = $session_start . '000';
    my $end_msec = $session_end . '000';
    my $until_msec = $until . '000';
    
    my %insert_data = (
	name => 'tests, generated by t/soap-session-recurring.t',
	facilitatorId => Elive->login->userId,
	password => 'sssh!',
	privateMeeting => 1,
	restrictedMeeting => 1,

	start =>  $start_msec,
	end => $end_msec,
	until => $until_msec,

	repeatEvery => 1,
	repeatSessionInterval => 1,
    );

    my @sessions = $class->insert(\%insert_data);

    my $n;
    foreach (@sessions) {
	isa_ok($_, $class, "session occurence ".++$n);
    }

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

    #
    # very approximate test on the dates being about a day apart. Allow
    # times could be out by over 1.5 hours due to daylight savings etc. 
##    diag((scalar localtime($start_times[0])).' vs '.(scalar localtime($start_times[1])));

    ok(t::Elive::a_day_between($start_times[0], $start_times[1]),
		       "sessions 1 & 2 separated by day week (approx)");

##    diag((scalar localtime($start_times[1])).' vs '.(scalar localtime($start_times[2])));
    ok(t::Elive::a_day_between($start_times[1], $start_times[2]),
       "sessions 2 & 3 separated by one day (approx)");

    $_->delete for @sessions;
}

Elive->disconnect;

