package NGCP::Redis;

use strict;
use warnings;

use Redis;
use Try::Tiny;

our $VERSION = '0.01';
our $DEBUG = 0;

sub new
{
    my ($this, %opts) = @_;
    my $class = ref $this || $this;

    my $self;
    eval {
        $self = Redis->new(%opts);
        bless $self, $class;
    } or do {
        ## no critic (Subroutines::ProhibitNestedSubs)
        sub NGCP::RedisMock::AUTOLOAD { return; };
        ## use critic

        $self = bless {}, 'NGCP::RedisMock';
    };

    return $self;
}

sub can
{
    my ($self, $method) = @_;

    return $self->SUPER::can($method);
}

our $AUTOLOAD;
sub AUTOLOAD
{
    my ($self, @opts) = @_;
    my $called = $AUTOLOAD =~ s/NGCP:://r;

    if ($called =~ m/Redis::_/) {
        print "D: passthrough -> $called\n" if $DEBUG;
        goto &{$called};
    }

    return try {
        print "D: try -> $called\n" if $DEBUG;
        return $self->$called(@opts);
    } catch {
        print "D: catch -> $called: '$_'\n" if $DEBUG;
        return;
    };
}

1;

__END__

=head1 NAME

NGCP::Redis - wrapper over Redis module to make it reliable

=head1 VERSION

Version 0.01

=head1 DESCRIPTION

This module will wrap the Redis module, and catch any exceptions and instead
make the subs return an undefined value.

=head1 AUTHOR

Guillem Jover, C<< <gjover@sipwise.com> >>

=head1 BUGS

Please report any bugs to Sipwise GmbH.

=head1 LICENSE

Copyright (c) 2018 Sipwise GmbH, Austria.

GPL-3+, Sipwise GmbH, Austria.

=cut
