package Pcore::API::Moz v0.7.0;

use Pcore -dist, -class, -result;
use Pcore::API::Moz::Account;

has api_expires => ( is => 'ro', isa => PositiveInt, default => 172_800 );    # in seconds, 2 days
has proxy_pool => ( is => 'ro', isa => Maybe [ InstanceOf ['Pcore::API::ProxyPool'] ] );

has invalid_accounts => ( is => 'ro', isa => ArrayRef, init_arg => undef );
has _valid_accounts  => ( is => 'ro', isa => ArrayRef, init_arg => undef );

sub BUILD ( $self, $args ) {
    for my $id ( keys $args->{api}->%* ) {
        push $self->{invalid_accounts}->@*, Pcore::API::Moz::Account->new( { moz => $self, id => $id, key => $args->{api}->{$id} } );
    }

    return;
}

sub check ( $self, $cb = undef ) {
    my $blocking_cv = defined wantarray ? AE::cv : undef;

    my $invalid_accounts = $self->{invalid_accounts};

    delete $self->{invalid_accounts};

    my $cv = AE::cv sub {
        $cb->( $self->{invalid_accounts} ) if $cb;

        $blocking_cv->( $self->{invalid_accounts} ) if $blocking_cv;

        return;
    };

    $cv->begin;

    for my $acc ( $invalid_accounts->@* ) {
        $cv->begin;

        $acc->get_url_metrics(
            ['google.com'],
            103_079_215_104,
            sub ($res) {
                $acc->{reason} = $res->{reason};

                if ($res) {
                    push $self->{_valid_accounts}->@*, $acc;
                }
                else {
                    push $self->{invalid_accounts}->@*, $acc;
                }

                $cv->end;

                return;
            }
        );
    }

    $cv->end;

    return $blocking_cv ? $blocking_cv->recv : ();
}

sub has_threads ($self) {
    return scalar $self->{_valid_accounts}->@*;
}

sub get_url_metrics ( $self, $domains, $metric, $cb ) {
    if ( $domains->@* > 10 ) {
        $cb->( result [ 999, q[Max. 10 domains are allowed per search request] ] );

        return;
    }

    # get random not busy account
    if ( my $acc = shift $self->{_valid_accounts}->@* ) {
        $acc->get_url_metrics(
            $domains, $metric,
            sub($res) {
                push $self->{_valid_accounts}->@*, $acc;

                $cb->($res);

                return;
            }
        );
    }

    # no free accounts available
    else {
        $cb->( result [ 999, q[No threads available] ] );
    }

    return;
}

1;
__END__
=pod

=encoding utf8

=head1 NAME

Pcore::API::Moz

=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 ATTRIBUTES

=head1 METHODS

=head1 SEE ALSO

=head1 AUTHOR

zdm <zdm@softvisio.net>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by zdm.

=cut
