package Link::Accounts::Remote;

use 5.014002;
use strict;
use warnings;
use RPC::XML;
use Net::Domain;
use Net::DNS;
use base qw(RPC::XML::Client);
$RPC::XML::ENCODING = 'utf-8';

our $VERSION = '0.01';

our $ERROR;

sub new {
    my ($class, $url) = @_;

    $url ||= find_la_url() or do {
        # ...
        return;
    };

    my $self = RPC::XML::Client->new($url);

    # Don't check certificate:
    #$self->useragent->ssl_opts(verify_hostname => 0);

    bless $self, $class;
}

sub find_la_url {
    my $domain = Net::Domain::hostdomain() or return;

    my $res = Net::DNS::Resolver->new;
    if (my $query = $res->query("_link_accounts.$domain", 'TXT')) {
        foreach my $rr ($query->answer) {
            $rr->type eq 'TXT' or next;
            return $rr->txtdata if $rr->txtdata;
        }
    }
    return;
}

sub query {
    my ($self, @args) = @_;

    my $res = $self->send_request(@args);
    if (!$res) {
        $ERROR = $RPC::XML::ERROR;
        return undef;
    } elsif (ref $res && !$res->is_fault) {
        return @{$res->value};
    } else {
        $ERROR = $res->string;
        return;
   }
}

1;

__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

Link::Accounts::Remote - Perl extension for blah blah blah

=head1 SYNOPSIS

  use Link::Accounts::Remote;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for Link::Accounts::Remote, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.


=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

olivier, E<lt>olivier@(none)E<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2011 by olivier

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.14.2 or,
at your option, any later version of Perl 5 you may have available.


=cut
