package Parp::IdCache;

=head1 NAME

Parp::IdCache - message ID cache management 

=head1 SYNOPSIS

Used internally.

=head1 DESCRIPTION

This module provides routines for managing the database of recently
delivered message IDs.  The database gets used when duplicate
avoidance is turned on via the C<-d> option (see L<Parp::Options>).

=cut

use strict;
use warnings;

use DB_File;
use Fcntl qw(:DEFAULT);

use Parp::Config qw(config);
use Parp::Locking;

use base 'Exporter';
our@EXPORT_OK = qw(is_duplicate);

use constant LOCK_IDENT => 'IdCache';

my @dup_ids = ();

sub attach {
  if (config->id_cache) {
    lock_ident(LOCK_IDENT);
    tie @dup_ids, 'DB_File', config->id_cache, O_CREAT | O_RDWR, 0600,
      $DB_RECNO;
  }
}

sub release {
  # Avoid `1 inner references still exist' warnings
  my $tied = tied @dup_ids ? 1 : 0;
  $tied and untie @dup_ids;
  unlock_ident(LOCK_IDENT);
}

sub is_duplicate {
  my ($id) = @_;

  # Ugh.  Wish there were tie-able dual array/hash data structures.
  # TODO: Maybe there are.  Find out.
  foreach my $cached_id (@dup_ids) {
    if ($id eq $cached_id) {
      return 1;
    }
  }

  return 0;
}

sub add_id {
  my ($id) = @_;
  
  push @dup_ids, $id;
  shift @dup_ids if @dup_ids > config->max_cache_ids;
}

1;

