package Common::RSDB::Clients;

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use base 'Class::Accessor';

use lib '/app/tools/common/lib';
use Common::RSDB;
use Common::RSDB::Client;

__PACKAGE__->mk_accessors(qw/clients/);

sub new {
    my $class = shift;
    my $self  = {};
    bless $self, $class;
    $self->_init();
    $self;
}

sub _init {
    my $self = shift;
    my $clients;
    foreach my $clientId ( Common::RSDB::GetAllClientIDs() ) {
        my $client = Common::RSDB::Client->new( $clientId, 1 );
        $clients->{'by_id'}->{$clientId} = $client;
        $clients->{'by_name'}->{ $client->dbname } = $client;
    }
    $self->clients($clients);
}

sub bookPubClients {
    my $clients;
    foreach my $clientId ( Common::RSDB::GetAllBookPubClientIDs() ) {
        my $client = Common::RSDB::Client->new( $clientId, 1 );
        push @{$clients}, $client;
    }
    $clients;
}

sub find {
    my $self = shift;
    my $data = shift;
    my $client =
      defined $self->clients->{'by_id'}->{$data}
      ? $self->clients->{'by_id'}->{$data}
      : $self->clients->{'by_name'}->{$data};
    $client;
}

sub _array {
    my $self = shift;
    my $type = shift;
    my $aref;
    foreach my $k ( keys %{ $self->clients->{$type} } ) {
        push @{$aref}, $self->clients->{$type}->{$k};
    }
    $aref;
}

sub by_id { shift->_array('by_id') }

sub by_name { shift->_array('by_name') }

sub by_host {
    my $self = shift;
    my $host;
    foreach my $c ( @{ $self->by_name } ) {
        next if $c->is_test;
        next if $c->client_type =~ m/other/i;
        push @{ $host->{ $c->server } }, $c if defined $c->server;
    }
    $host;
}

1;
