#!perl
use warnings; use strict;
use Test::More tests => 37;
use Test::Fatal;

use version;
use Try::Tiny;

use lib '.';
use t::Bb::Collaborate::V3;

use Bb::Collaborate::V3::Session;
use Elive::Util;

our $t = Test::More->builder;
our $class = 'Bb::Collaborate::V3::Session';

our $connection;

SKIP: {

    my $skippable = 37;

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

   skip ($result{reason} || 'skipping live tests', $skippable)
	unless $auth && @$auth;

    try {require Bb::Collaborate::V3::Connection} catch {die $_};

    my $connection_class = $result{class};
    $connection = $connection_class->connect(@$auth);
    Bb::Collaborate::V3->connection($connection);

    my $session_start = Elive::Util::next_quarter_hour();
    my $session_end = Elive::Util::next_quarter_hour( $session_start );

    my %session_data = (
	sessionName => 'test session, generated by t/soap-session.t',
	creatorId => $connection->user,
	startTime =>  $session_start . '000',
	endTime => $session_end . '000',
	openChair => 0,
	mustBeSupervised => 0,
	permissionsOn => 1,
	chairList => [qw(alice bob)],
	groupingList => [qw(mechanics sewing)],
    );

    my $session = $class->insert(\%session_data);

    isa_ok($session, $class, 'session');
    ok(my $session_id = $session->sessionId, 'Insert returned session id');

    note "session-id: $session_id";

    foreach (keys %session_data) {
	#
	# returned record doesn't contain password
	is(uc Elive::Util::string($session->$_), uc Elive::Util::string($session_data{$_}), "session $_ as expected");
    }

    my %update_data = (
	chairNotes => 'test moderator notes. Here are some entities: & > <',
	nonChairNotes => 'test user notes; some more entities: &gt;',
	raiseHandOnEnter => 1,
	maxTalkers => 3,
	recordingModeType => 2,
	);

    $session->update(\%update_data);

    is( exception {$session->set_api_callback_url('http://perlmonks.org')} => undef,
	'$session->setapI_callback_url(...) - lives');

    my %class_level_session_update = (
	sessionId => $session->sessionId,
	sessionName => 'test session, generated by t/soap-session.t',
	creatorId => $connection->user,
	startTime =>  $session_start . '000',
	endTime => $session_end . '000',
	raiseHandOnEnter => 0,
	chairNotes => 'This session updated from class level',
	);

    is( exception {Bb::Collaborate::V3::Session->update(\%class_level_session_update)} => undef,
	'class level update');

    for (keys %class_level_session_update) {
	$update_data{$_} = $class_level_session_update{$_};
    }

    my $sessions;

    # time-interval should include the meeting that was just created.
    my $end_time = $session_start + 240;
    my $start_time = $end_time  -  60 * 60 * 24 * 7; # one weeks approx

    use Carp; $SIG{__DIE__} = \&Carp::confess;
    is( exception {
	$sessions = Bb::Collaborate::V3::Session->list(filter => {startTime => $start_time.'000', endTime => $end_time.'000'})
	  } => undef,
	'list sessions by date');


    my ($this_session, @_gunk) = grep {$_->sessionId == $session->sessionId} @$sessions;
    note "found @{[ scalar @$sessions ]} sessions over the last week";
    ok $this_session, "found current session by date range";
    ok( !(scalar @_gunk), "current session by date range is unique");

    foreach my $s (@$sessions) {
	next if $s->sessionId == $session->sessionId
	    || lc($s->sessionName) ne 'test session, generated by t/soap-session.t';
        warn "junk session @{[ $s->sessionId ]}: @{[ $s->sessionName ]}";
	$s->delete;
    }

    ok ($sessions = Bb::Collaborate::V3::Session->list(filter => {sessionId => $session_id}),
	'list sessions by id');
  
    is(scalar @$sessions, 1, 'list returns unique session');

    is( try {$sessions->[0]->sessionId}, $session_id, 'listed sessionId as expected');
    $sessions = undef;

    $session = undef;

    ok ($session = Bb::Collaborate::V3::Session->retrieve($session_id),
	'Refetch of session');

    foreach (keys %update_data) {
	#
	# returned record doesn't contain password
	is( uc $session->$_, uc $update_data{$_}, "session update $_ as expected");
    }

    my $session_url;
    is( exception {$session_url = $session->session_url(userId => 'bob', displayName => 'Robert')} => undef, 'Can generate session Url for charList user');
    note "session url: $session_url";

    my %attendee = (userId => 'fred', displayName => 'Frederick Nurk', isChair => 1);
    my $url;
    is exception {$url = $session->register_attendee(\%attendee)} => undef, 'Register_attendee lives';
    note "attendee_url: $url";
    ok $url, "got attendee_url";

    my $attendances;

    is( exception {$attendances = $session->attendance('')} => undef, 'session attendance sans date - lives');

    my $today = $session_start - 7200;
    is( exception {$attendances = $session->attendance($today . '000')} => undef, 'session attendance with date - lives');

    is( exception {Bb::Collaborate::V3::Session->delete(sessionId => $session_id)} => undef, 'session deletion (class level) - lives');

    my $deleted_session;
    my $del_error = exception {$deleted_session = Bb::Collaborate::V3::Session->retrieve($session_id)};

    ok($del_error || !$deleted_session, "can't retrieve deleted session");
}

Bb::Collaborate::V3->disconnect;

