package BroadWorks::OCI;

use 5.006;
use strict;
use warnings 'all';

use XML::Compile::Cache;
use Log::Report 'broadworks-oci', syntax => 'SHORT';
use IO::Socket::INET;
use IO::Socket::Timeout;
use Errno qw(ETIMEDOUT EWOULDBLOCK);
use Digest::MD5;
use Digest::SHA;

use Moose;
use MooseX::ClassAttribute;

use File::ShareDir;

class_has '_XCC' => (
  is      => 'ro',
  lazy    => 1,
  default => sub { {} },
);

sub XCC {
  my $self = shift;
  my $schema = shift;
  $self->_XCC->{$schema} ||= $self->_build_XCC($schema);
}

sub _build_XCC {
  my $self = shift;
  my $schema = shift;
  my @path = split('/', $schema);
  $schema = pop @path;
  $schema = join('/', 'OCISchemaAS', @path) .
              '/OCISchema' . $schema . '.xsd';
  info "Loading $schema";

  my $dist_dir = File::ShareDir::dist_dir('BroadWorks-OCI');
  my @schemata = (
    "OCISchemaBASE/OCISchemaBASE.xsd",
    "OCISchemaAS/OCISchemaDataTypes.xsd",
    "OCISchemaAS/OCISchemaSearchCriteria.xsd",
    "OCISchemaAS/OCISchemaSortCriteria.xsd",
    $schema,
  );

  # results in some repeat inclusion of BASE and DataTypes, but not in
  # importing a huge pile of definitions we aren't going to use
  my $XCC = XML::Compile::Cache->new(
    \@schemata,
    schema_dirs => $dist_dir,
    xsi_type => {
      '{C}OCICommand' => 'AUTO',
    },
  );
  # we only ever send/receive one type of root element
  $XCC->declare(RW => '{C}BroadsoftDocument');

  return $XCC;
}

sub reader {
  my $self = shift;
  my $schema = shift;
  $self->XCC($schema)->reader('{C}BroadsoftDocument');
}

sub writer {
  my $self = shift;
  my $schema = shift;
  $self->XCC($schema)->writer('{C}BroadsoftDocument');
}

has 'sessionId' => (
  is      => 'ro',
  default => sub {
    Digest::MD5::md5_hex(time().{}.rand().$$);
  },
);

has 'hostname' => (
  is      => 'ro',
  default => 'ews.xdp.broadsoft.com', # test server
);

has 'port' => (
  is      => 'ro',
  default => 2208,
);

has 'socket' => (
  is      => 'rw',
  lazy    => 1,
  builder => '_connect',
);

has 'timeout' => (
  is      => 'rw',
  default => 30,
);

sub _connect {
  my $self = shift;
  my $host = $self->hostname;
  my $port = $self->port;
  info("opening socket to $host:$port");
  my $socket = IO::Socket::INET->new(
    PeerAddr => $host,
    PeerPort => $port,
    Proto    => 'tcp',
    Timeout  => $self->timeout,
  ) or die "failed to connect: $!\n";

  IO::Socket::Timeout->enable_timeouts_on($socket);
  $socket->read_timeout($self->timeout);
  $socket->write_timeout($self->timeout);

  return $socket;
}

has 'userId' => (
  is        => 'ro',
  required  => 1,
);

has 'password' => (
  is        => 'ro',
  required  => 1,
);

sub request {
  my $self = shift;
  my $schema = shift;
  my $command = shift;

  my %args;
  if (ref($_[0])) {
    %args = %{ $_[0] };
  } else {
    %args = @_;
  }
  # XML::Compile's way to deal with the "xsi:type=" attribute for late-binding
  # element types:
  $args{'XSI_TYPE'} = $command;

  my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
  info("sending $command");
  my $content = {
    'sessionId' => $self->sessionId,
    'protocol'  => 'OCI',
    'command'   => \%args,
  };

  # format and send request
  local $@;
  eval {
    $doc->setDocumentElement( $self->writer($schema)->( $doc, $content ) );
    trace("$doc\n\n");
    $self->socket->print("$doc");
  };
  return (0, $@) if $@;

  local $!;
  # responses from the API are _usually_ two lines, but sometimes only one.
  my $xml_response = $self->socket->getline;
  if ($xml_response and $xml_response !~ m[</BroadsoftDocument]) {
    $xml_response .= $self->socket->getline;
  }
  if (!$xml_response and ($! == ETIMEDOUT or $! == EWOULDBLOCK)) {
    return (0, 'OCI request timed out');
  }

  # parse response
  trace("$xml_response\n\n");
  my $response = eval { $self->reader($schema)->( $xml_response ) };
  return (0, $@) if $@;

  $command = $response->{command};
  $command = $command->[0] if ref($command) eq 'ARRAY';

  my $response_type = $command->{XSI_TYPE};
  if ($response_type eq 'SuccessResponse') {
    return (1, '');
  } elsif ( $response_type eq '{C}ErrorResponse' ) {
    return (0, $command->{summary});
  } else { # all other response types
    info("received document type '$response_type'");
    return (1, $command);
  }
}

sub login {
  my $self = shift;
  my ($success, $message) = $self->request( 'Login', 'AuthenticationRequest',
    userId => $self->userId,
  );
  return ($success, $message) unless $success;

  # construct challenge response
  my $token = Digest::MD5::md5_hex(
    $message->{nonce} . ':' . Digest::SHA::sha1_hex($self->password)
  );
  return $self->request('Login', 'LoginRequest14sp4',
    userId => $self->userId,
    signedPassword => $token,
  );
}

sub BUILD {
  my $self = shift;
  my ($success, $message) = $self->login;
  die "Login failed: $message" if !$success;
  $self;
}

=head1 NAME

BroadWorks::OCI - Open Client Interface for BroadWorks Application Server.

=head1 VERSION

Version 0.01

=cut

our $VERSION = '0.01';

=head1 SYNOPSIS

Quick summary of what the module does.

Perhaps a little code snippet.

    use BroadWorks::OCI;

    my $foo = BroadWorks::OCI->new();
    ...

=head1 METHODS

=cut

=head1 AUTHOR

Mark Wells, C<< <mark at freeside.biz> >>


=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc BroadWorks::OCI


You can also look for information at:

=over 4

=item * RT: CPAN's request tracker (report bugs here)

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=BroadWorks-OCI>

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/BroadWorks-OCI>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/BroadWorks-OCI>

=item * Search CPAN

L<http://search.cpan.org/dist/BroadWorks-OCI/>

=back


=head1 ACKNOWLEDGEMENTS


=head1 LICENSE AND COPYRIGHT

Copyright 2015 Mark Wells.

This program is free software; you can redistribute it and/or modify it
under the terms of the the Artistic License (2.0). You may obtain a
copy of the full license at:

L<http://www.perlfoundation.org/artistic_license_2_0>

Any use, modification, and distribution of the Standard or Modified
Versions is governed by this Artistic License. By using, modifying or
distributing the Package, you accept this license. Do not use, modify,
or distribute the Package, if you do not accept this license.

If your Modified Version has been derived from a Modified Version made
by someone other than you, you are nevertheless required to ensure that
your Modified Version complies with the requirements of this license.

This license does not grant you the right to use any trademark, service
mark, tradename, or logo of the Copyright Holder.

This license includes the non-exclusive, worldwide, free-of-charge
patent license to make, have made, use, offer to sell, sell, import and
otherwise transfer the Package with respect to any patent claims
licensable by the Copyright Holder that are necessarily infringed by the
Package. If you institute patent litigation (including a cross-claim or
counterclaim) against any party alleging that the Package constitutes
direct or contributory patent infringement, then this Artistic License
to you shall terminate on the date that such litigation is filed.

Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


=cut

1; # End of BroadWorks::OCI
