package Mud::Storage::NamedFiles;
use strict;
use Mud::CoreTools;
use Mud::Storage;
use vars qw(@ISA);
@ISA = qw(Mud::Storage);
use POSIX qw(:errno_h);

use constant DATA_DIR => 'objects/nf/';

=head1 Description

Mud::Storage::NamedFiles is a storage object which keeps each object in
a separate file, and identifies objects by names.

=cut

### Initialization ########################################

__PACKAGE__->register_storage('nf');

### Methods #############################################################

=head1 Methods

=over 4

=cut

sub real_obj {
  my ($self, $key) = @_;
  my $o = (
    $self->cache_get($key, 1)
    or do {
      $key =~ /([^-_.A-Za-z0-9])/
        and croak "Disallowed character '$1' in object key '$key'";
        
      my $p;
      my $fh = Mud::FS->open($p = DATA_DIR . $key . ".tobj", '<') or do {
        if ($! == ENOENT) {
          mudlog "DEBUG: btw, $p not found";
          return undef;
        } else {
          croak "Unexpected error while opening '$p': $!";
        }
      };
      <$fh> eq "NamedFiles Object v1\n" or croak "Unknown file format: $p";
      <$fh> =~ /^(.*)$/ or die "can't happen"; # untaint
      my $class = $1;
      do {local $/; <$fh>} =~ /^(.*)$/s or die "can't happen"; # untaint
      my $data = $1;
      my $dobj = \$data;
      eval "require $class";
      bless $dobj, $class;
      my $obj = $dobj->storage_create_from_data('text');
      
      $self->cache_add($key, $obj);
      $obj;
    }
  );
  
  #print "#$%", Data::Dumper::Dumper($o), "\n";
  $o;
}

sub object_changed {
  my ($self, $obj) = @_;
  $self->cache_dirty($obj->storage_get_cookie);
}

sub cache_write {
  my ($self, $obj) = @_;
  warn "Writing NamedFile not yet implemented!";
  $self->SUPER::cache_write($obj);
}

=back

=cut

1;
__END__