#  You may distribute under the terms of either the GNU General Public License
#  or the Artistic License (the same terms as Perl itself)
#
#  (C) Paul Evans, 2016 -- leonerd@leonerd.org.uk

package Net::Prometheus::Gauge;

use strict;
use warnings;
use base qw( Net::Prometheus::Metric );

our $VERSION = '0.02';

use Carp;

use constant _type => "gauge";

=head1 NAME

C<Net::Prometheus::Gauge> - a snapshot value-reporting metric

=head1 SYNOPSIS

   use Net::Prometheus;

   my $client = Net::Prometheus->new;

   my $gauge = $client->new_gauge(
      name => "users",
      help => "Number of current users",
   );

   my %users;
   ...

   $gauge->set( scalar keys %users );

=head1 DESCRIPTION

This class provides a gauge metric - an arbitrary value that observes some
snapshot of state at some instant in time. This is often used to report on the
current usage of resources by the instrumented program, in a way that can
decrease as well as increase. It is a subclass of L<Net::Prometheus::Metric>.

=cut

=head1 CONSTRUCTOR

Instances of this class are not usually constructed directly, but instead via
the L<Net::Prometheus> object that will serve it:

   $gauge = $prometheus->new_gauge( %args )

This takes the same constructor arguments as documented in
L<Net::Prometheus::Metric>.

=cut

__PACKAGE__->make_childlabel_method( $_ ) for qw( set inc dec );

sub new
{
   my $class = shift;

   my $self = $class->SUPER::new( @_ );

   $self->{values} = {};

   return $self;
}

=head1 METHODS

=cut

=head2 set

   $gauge->set( [ @label_values ], $value )

   $child->set( $value )

Sets the current value for the gauge.

If the gauge has any labels defined, the values for them must be given first.

=cut

sub _set_child
{
   my $self = shift;
   my ( $labelkey, $value ) = @_;

   $self->{values}{$labelkey} = $value;
}

=head2 inc

   $gauge->inc( [ @label_values ], $delta )

   $child->inc( $delta )

Increment the current value for the gauge. C<$delta> will default to 1 if not
supplied.

=cut

sub _inc_child
{
   my $self = shift;
   my ( $labelkey, $delta ) = @_;
   defined $delta or $delta = 1;

   $self->{values}{$labelkey} += $delta;
}

=head2 dec

   $gauge->dec( [ @label_values ], $delta )

Decrement the current value for the gauge. C<$delta> will default to 1 if not
supplied.

=cut

sub _dec_child
{
   my $self = shift;
   my ( $labelkey, $delta ) = @_;
   defined $delta or $delta = 1;

   $self->{values}{$labelkey} -= $delta;
}

sub samples
{
   my $self = shift;

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

   return map {
      $self->make_sample( undef, $_, $values->{$_} )
   } sort keys %$values;
}

=head1 AUTHOR

Paul Evans <leonerd@leonerd.org.uk>

=cut

0x55AA;
