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

use version;

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

use Bb::Collaborate::V3::Session;
use Bb::Collaborate::V3::Session::Telephony;

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

our $connection;

SKIP: {

    my $skippable = 11;

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

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

    use Bb::Collaborate::V3::Connection;
    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 );

    $session_start .= '000';
    $session_end .= '000';

    my %session_data = (
	sessionName => 'test session, generated by t/soap-session-telephony.t',
	creatorId => $connection->user,
	startTime =>  $session_start,
	endTime => $session_end,
    );

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

    my $session_telephony;
    is( exception {$session_telephony = $session->telephony} => undef, 'get session telephony - lives');

    my %telephony_data = (
        telephonyType => 'thirdParty',
	chairPhone => '1 123 123 1234',
	chairPIN   => '6342',
	nonChairPhone => '1 248 248 0248',
	nonChairPIN   => '7722',
	isPhone => '0',
	sessionSIPPhone => 'sip:foo@bar.com',
	sessionPIN => '1234',
	);

    is( exception {$session_telephony->update(\%telephony_data)} => undef, 'telephony update - lives');

    $session_telephony = undef;
    my $session_id = $session->sessionId;

    is( exception {$session_telephony = Bb::Collaborate::V3::Session::Telephony->retrieve($session_id)} => undef,
	     'retrieve session telephony - lives');

    foreach (grep {$_ ne 'telephonyType'} sort keys %telephony_data) {
        is($session_telephony->$_, $telephony_data{$_}, "session telephony: $_ - as expected");
    }

    $session_telephony->isPhone(1);
    is exception {$session_telephony->update} => undef, 'update $telephony->isPhone - lives';

    $session->delete;

    my $end_time = time() + 240;
    my $start_time = $end_time  -  60 * 60 * 24 * 7; # one weeks approx

    my $sessions = Bb::Collaborate::V3::Session->list(filter => {startTime => $start_time.'000', endTime => $end_time.'000'});

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

}

Bb::Collaborate::V3->disconnect;

