#
# Module Generated by Template::Tiny on [% date %]
#

package ZMQ::FFI::[% zmqver %]::Context;

use FFI::Platypus;
use ZMQ::FFI::Util qw(zmq_soname current_tid);
use ZMQ::FFI::Constants qw(:all);
use ZMQ::FFI::[% zmqver %]::Socket;
use ZMQ::FFI::[% zmqver %]::Raw;
use ZMQ::FFI::Custom::Raw;
use Try::Tiny;
use Scalar::Util qw(weaken);
[% lib_imports %]
use Moo;
use namespace::clean;

with qw(
    ZMQ::FFI::ContextRole
    ZMQ::FFI::ErrorHelper
    ZMQ::FFI::Versioner
);

my $FFI_LOADED;

sub BUILD {
    my ($self) = @_;

    unless ($FFI_LOADED) {
        ZMQ::FFI::Custom::Raw::load($self->soname);
        ZMQ::FFI::[% zmqver %]::Raw::load($self->soname);
        $FFI_LOADED = 1;
    }

    $self->init()
}

[% FOREACH method IN api_methods %]
[%- [%- method -%] -%]
[% END %]

sub _add_socket {
    my ($self, $socket) = @_;
    weaken($self->sockets->{$socket} = $socket);
}

sub _remove_socket {
    my ($self, $socket) = @_;
    delete($self->sockets->{$socket});
}

sub DEMOLISH {
    my ($self) = @_;

    return if $self->context_ptr == -1;

    # check defined to guard against
    # undef objects during global destruction
    if (defined $self->sockets) {
        for my $socket_k (keys %{$self->sockets}) {
            my $socket = $self->_remove_socket($socket_k);
            $socket->close()
                if defined $socket && $socket->socket_ptr != -1;
        }
    }

    $self->destroy();
}

1;

# vim:ft=perl