# -*-perl-*-
#
# $Id$
#
# Key management
#
# (c) 2004 Straylight/Edgeware
#

#----- Licensing notice -----------------------------------------------------
#
# This file is part of the Perl interface to Catacomb.
#
# Catacomb/Perl is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# Catacomb/Perl is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Catacomb/Perl; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#----- Key data -------------------------------------------------------------

package Catacomb::Key::Data::StructTie;
use Carp;
use Catacomb::Base;

sub TIEHASH { bless [$_[1], []], $_[0]; }
sub FETCH { $_[0][0]->find($_[1]); }
sub EXISTS { !!$_[0][0]->find($_[1]); }
sub DELETE { $_[0][0]->del($_[1]); }
sub STORE { $_[0][0]->find($_[1], $_[2]); }

sub CLEAR {
  my ($me) = @_;
  my $kd = $me->[0];
  my $i = $kd->iterate();
  $kd->del($k) while my $k = $i->next();
  1;
}

sub FIRSTKEY {
  my ($me) = @_;
  my $kd = $me->[0];
  my $i = $kd->iterate();
  my @k = ();
  while (my $k = $i->next()) {
    push(@k, $k);
  }
  $me->[1] = \@k;
  return shift(@k);
}
sub NEXTKEY { shift(@{$_[0][1]}); }

package Catacomb::Key::Data::Structured;
sub open {  my %h; tie %h, Catacomb::Key::Data::StructTie, $_[0]; \%h; }

foreach $i (qw(Binary Encrypted MP EC String Structured)) {
  @{"Catacomb::Key::Data::${i}::ISA"} = qw(Catacomb::Key::Data);
}

#----- Actual keys ----------------------------------------------------------

package Catacomb::Key::Attrs;
use Carp;

sub TIEHASH { bless [$_[1], []], $_[0]; }
sub FETCH { $_[0][0]->getattr($_[1]); }
sub EXISTS { defined($_[0][0]->getattr($_[1])); }
sub STORE { $_[0][0]->putattr($_[1], $_[2]); }
sub DELETE { $_[0][0]->putattr($_[1]); }
sub FIRSTKEY {
  my ($me) = @_;
  my $k = $me->[0];
  my $i = $k->attriter();
  my @a;
  while (my $a = $i->next()) { push(@a, $a); }
  $me->[1] = \@a;
  return shift(@a);
}
sub NEXTKEY { shift(@{$_[0][1]}); }

package Catacomb::Key;

sub attrs {
  croak("Usage: Catacomb::Key::attrs(k)") unless @_ == 1;
  my %a;
  tie %a, Catacomb::Key::Attrs, @_;
  return \%a;
}

#----- That's all, folks ----------------------------------------------------

1;
