package WebService::NetSuite::SuiteTalk::Role::Connection;

use Modern::Perl '2011';    ## no critic (Modules::ProhibitUseQuotedVersion)

our $VERSION = '0.003';     # TRIAL VERSION
use utf8;
use re '/xms';
use CHI;
use List::Util 'first';
use Log::Report;
use Log::Report::Die;
use Moo::Role;
use MooX::Types::MooseLike::Base qw(Bool CodeRef HashRef InstanceOf Str);
use MooX::Types::MooseLike::Email 'EmailAddressLoose';
use Scalar::Util 'blessed';
use URI;
use WWW::Mechanize::Cached;
use XML::Compile::WSDL11;
use XML::Compile::SOAP11;
use XML::Compile::Transport::SOAPHTTP;
use XML::Compile::Util 'SCHEMA2001';
use XML::CompileX::Schema::Loader;

has account_id => ( is => 'rwp', isa => Str, trigger => \&_build_passport );
has password   => ( is => 'rwp', isa => Str, trigger => \&_build_passport );
has user_role => ( is => 'ro', isa => HashRef, predicate => 1 );
has passport => ( is => 'lazy', isa => HashRef );

has email_address => (
    is      => 'rwp',
    isa     => EmailAddressLoose,
    trigger => \&_build_passport,
);

sub _build_passport {
    my $self     = shift;
    my %passport = (
        email    => $self->email_address,
        password => $self->password,
        account  => $self->account_id,
    );
    if ( $self->has_user_role ) { $passport{role} = $self->user_role }
    return \%passport;
}

has endpoint => (
    is     => 'rwp',
    isa    => InstanceOf ['URI'],
    coerce => sub {
        defined blessed( $_[0] )
            && $_[0]->isa('URI') ? $_[0] : URI->new( $_[0] );
    },
    default => sub {
        URI->new(
            'https://webservices.netsuite.com/wsdl/v2014_2_0/netsuite.wsdl');
    },
);

has xsi_auto => ( is => 'ro', isa => Bool, default => 0 );
has debug    => ( is => 'ro', isa => Bool, default => 0 );

has _datacenter_uris =>
    ( is => 'lazy', isa => HashRef [ InstanceOf ['URI'] ] );

sub _build__datacenter_uris {
    my $self = shift;

    my $loader = XML::CompileX::Schema::Loader->new(
        uris       => $self->endpoint,
        wsdl       => $self->_wsdl,
        user_agent => $self->user_agent,
    );
    $loader->collect_imports;

    my ( $answer_ref, $trace )
        = $loader->wsdl->compileClient('getDataCenterUrls')
        ->( account => $self->account_id );

    ## no critic (ValuesAndExpressions::ProhibitAccessOfPrivateData)
    if (   not $answer_ref
        or not $answer_ref->{parameters}{getDataCenterUrlsResult}{status}
        {isSuccess} )
    {
        for ( $trace->errors ) { $_->throw }
    }

    my %urls
        = %{ $answer_ref->{parameters}{getDataCenterUrlsResult}
            {dataCenterUrls} };
    return { map { $_ => URI->new( $urls{$_} ) } keys %urls };
}

has transport =>
    ( is => 'lazy', isa => InstanceOf ['XML::Compile::Transport::SOAPHTTP'] );

sub _build_transport {
    my $self         = shift;
    my $endpoint_uri = URI->new( $self->wsdl->endPoint );
    my $user_agent   = $self->user_agent;
    $user_agent->add_handler(
        request_prepare =>
            sub { $_[0]->header( SOAPAction => $self->_soap_action ) },
        (   'm_scheme'    => $endpoint_uri->scheme,
            'm_host_port' => $endpoint_uri->host_port,
            'm_path'      => $endpoint_uri->path,
            'm_method'    => 'POST',
        ),
    );
    return XML::Compile::Transport::SOAPHTTP->new(
        address    => $endpoint_uri,
        user_agent => $self->user_agent,
    );
}

has _soap_action => ( is => 'rw', isa => Str, default => q{} );

has _cache_datastore => ( is => 'rw', isa => HashRef, default => sub { {} } );

has user_agent => (
    is      => 'lazy',
    isa     => InstanceOf ['LWP::UserAgent'],
    default => sub {
        return WWW::Mechanize::Cached->new(
            cache => CHI->new(
                driver    => 'RawMemory',
                datastore => $_[0]->_cache_datastore,
            ),
        );
    },
);

has _wsdl => (
    is       => 'lazy',
    isa      => InstanceOf ['XML::Compile::WSDL11'],
    init_arg => undef,
    default  => sub { XML::Compile::WSDL11->new( allow_undeclared => 1 ) },
);

has _loader => (
    is      => 'lazy',
    isa     => InstanceOf ['XML::CompileX::Schema::Loader'],
    handles => ['wsdl'],
);

sub _build__loader {
    my $self     = shift;
    my $wsdl     = $self->_wsdl;
    my $endpoint = $self->_datacenter_uris->{webservicesDomain};

    # copy path query if any from starting endpoint
    $endpoint->path_query( $self->endpoint->path_query );

    my $loader = XML::CompileX::Schema::Loader->new(
        uris       => $endpoint,
        user_agent => $self->user_agent,
        wsdl       => $wsdl,
    );
    $loader->collect_imports;

    # import all complex abstract types from platformCore as xsiTypes
    if ( $self->xsi_auto ) {
        my $namespaces   = $wsdl->namespaces;
        my $core_ns_name = first {
            /\A urn:core_.*? [.]platform[.]webservices[.]netsuite[.]com \z/
        }
        $namespaces->list
            or die_decode(q{can't find core platform namespaces});
        my ($core_ns) = $namespaces->namespace($core_ns_name);
        $wsdl->addXsiType( $core_ns->types );
    }
    return $loader;
}

sub BUILD {
    my $self = shift;
    ## no critic (Subroutines::ProhibitCallsToUndeclaredSubs)
    if ( $self->debug ) { dispatcher( mode => 'DEBUG', 'ALL' ) }
    return;
}

1;

# ABSTRACT: Wrapper for NetSuite SuiteTalk web services

__END__

=pod

=encoding UTF-8

=for :stopwords Mark Gardner ZipRecruiter cpan testmatrix url annocpan anno bugtracker rt
cpants kwalitee diff irc mailto metadata placeholders metacpan

=head1 NAME

WebService::NetSuite::SuiteTalk::Role::Connection - Wrapper for NetSuite SuiteTalk web services

=head1 VERSION

version 0.003

=head1 SYNOPSIS

    use Moo;
    with 'WebService::NetSuite::SuiteTalk::Role::Connection';

=head1 DESCRIPTION

This role integrates
L<NetSuite SuiteTalk web services|http://www.netsuite.com/portal/platform/developer/suitetalk.shtml>.
Apart from basic web service proxying, it also handles selecting the correct
NetSuite data center on login.

To use as a plain Perl class, consult
L<WebService::NetSuite::SuiteTalk|WebService::NetSuite::SuiteTalk>.

=head1 ATTRIBUTES

=head2 account_id

The NetSuite account ID used for authentication.

=head2 email_address

The email address used for NetSuite authentication.

=head2 password

The password used for NetSuite authentication.

=head2 user_role

Optional name of the NetSuite role used for authorization.

=head2 endpoint

A L<URI|URI> object indicating the NetSuite WSDL file to load. Defaults to
L<https://webservices.netsuite.com/wsdl/v2014_2_0/netsuite.wsdl>, which is the
current NetSuite SuiteTalk API as of this writing.

=head2 wsdl

Read-only access to the L<XML::Compile::WSDL11|XML::Compile::WSDL11> instance used internally by this class.

=head2 debug

When set to true, the L<Log::Report|Log::Report> dispatcher used by
L<XML::Compile|XML::Compile> and friends is set to I<DEBUG> mode.

=head2 xsi_auto

When set to true, all complex abstract types from the NetSuite platformCore
schema are added as XML Schema Instance types.

=head1 METHODS

=head2 has_user_role

A predicate method that returns true if the C<user_role> attribute is set.

=for Pod::Coverage BUILD

=head1 SUPPORT

=head2 Perldoc

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

  perldoc WebService::NetSuite::SuiteTalk

=head2 Websites

The following websites have more information about this module, and may be of help to you. As always,
in addition to those websites please use your favorite search engine to discover more resources.

=over 4

=item *

MetaCPAN

A modern, open-source CPAN search engine, useful to view POD in HTML format.

L<http://metacpan.org/release/WebService-NetSuite-SuiteTalk>

=item *

Search CPAN

The default CPAN search engine, useful to view POD in HTML format.

L<http://search.cpan.org/dist/WebService-NetSuite-SuiteTalk>

=item *

AnnoCPAN

The AnnoCPAN is a website that allows community annotations of Perl module documentation.

L<http://annocpan.org/dist/WebService-NetSuite-SuiteTalk>

=item *

CPAN Ratings

The CPAN Ratings is a website that allows community ratings and reviews of Perl modules.

L<http://cpanratings.perl.org/d/WebService-NetSuite-SuiteTalk>

=item *

CPAN Forum

The CPAN Forum is a web forum for discussing Perl modules.

L<http://cpanforum.com/dist/WebService-NetSuite-SuiteTalk>

=item *

CPANTS

The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.

L<http://cpants.cpanauthors.org/dist/WebService-NetSuite-SuiteTalk>

=item *

CPAN Testers

The CPAN Testers is a network of smokers who run automated tests on uploaded CPAN distributions.

L<http://www.cpantesters.org/distro/W/WebService-NetSuite-SuiteTalk>

=item *

CPAN Testers Matrix

The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.

L<http://matrix.cpantesters.org/?dist=WebService-NetSuite-SuiteTalk>

=item *

CPAN Testers Dependencies

The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.

L<http://deps.cpantesters.org/?module=WebService::NetSuite::SuiteTalk>

=back

=head2 Bugs / Feature Requests

Please report any bugs or feature requests through the web
interface at
L<https://github.com/mjgardner/webservice-netsuite-suitetalk/issues>.
You will be automatically notified of any progress on the
request by the system.

=head2 Source Code

The code is open to the world, and available for you to hack on. Please feel free to browse it and play
with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull
from your repository :)

L<https://github.com/mjgardner/webservice-netsuite-suitetalk>

  git clone git://github.com/mjgardner/webservice-netsuite-suitetalk.git

=head1 AUTHOR

Mark Gardner <mjgardner@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by ZipRecruiter.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
