# ABSTRACT: A collection of Net::Object::Peer::Subscriptions
package Net::Object::Peer::Subscriptions;

use 5.10.0;
use strict;
use warnings;

our $VERSION = '0.01'; # TRIAL

use Types::Standard qw[ ArrayRef InstanceOf ];
use Ref::Util qw[ is_coderef ];
use List::Util qw[ all ];

use namespace::clean;

use Moo;

has _subscriptions => (
    is       => 'ro',
    init_arg => undef,
    isa      => ArrayRef [ InstanceOf ['Net::Object::Peer::Subscription'] ],
    default => sub { [] },
    lazy    => 1,
    clearer => 1,
);

#pod =method list
#pod
#pod =cut

sub list {
    return @{ $_[0]->_subscriptions };
}

#pod =method clear
#pod
#pod =cut

sub clear { $_[0]->_clear_subscriptions }

#pod =method add
#pod
#pod =cut

sub add {
    my $self = shift;

    push @{ $self->_subscriptions }, @_;

    return;
}

sub _find_index {

    my $self = shift;
    my $subs = $self->_subscriptions;

    if ( is_coderef( $_[0] ) ) {

        my $match = shift;
        return grep { $match->( $subs->[$_] ) } 0 .. @$subs - 1;

    }
    else {
        my %match = @_;

        return grep {
            my $sub = $subs->[$_];
            all { $sub->$_ eq $match{$_} } keys %match;
        } 0 .. @$subs - 1;
    }
}

#pod =method delete
#pod
#pod =cut

sub delete {

    my $self = shift;

    my $subs = $self->_subscriptions;

    # need to remove subscriptions from the back to front,
    # or indices get messed up
    my @indices = reverse sort $self->_find_index( @_ );

    return map { splice( @$subs, $_, 1 ) } @indices;

}

1;
#
# This file is part of Net-Object-Peer
#
# This software is Copyright (c) 2016 by Smithsonian Astrophysical Observatory.
#
# This is free software, licensed under:
#
#   The GNU General Public License, Version 3, June 2007
#

=pod

=head1 NAME

Net::Object::Peer::Subscriptions - A collection of Net::Object::Peer::Subscriptions

=head1 VERSION

version 0.01

=head1 DESCRIPTION

A B<Net::Object::Peer::Subscriptions> object manages a collection
of L<Net::Object::Peer::Subscriptions> objects.

=head1 METHODS

=head2 list

=head2 clear

=head2 add

=head2 delete

=head1 AUTHOR

Diab Jerius <djerius@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2016 by Smithsonian Astrophysical Observatory.

This is free software, licensed under:

  The GNU General Public License, Version 3, June 2007

=cut

__END__

#pod =head1 DESCRIPTION
#pod
#pod A B<Net::Object::Peer::Subscriptions> object manages a collection
#pod of L<Net::Object::Peer::Subscriptions> objects.
