#!/usr/bin/perl

use strict;
use warnings;

use Test::More tests => 24;
use File::Path qw( remove_tree );
use Fcntl;
# use Data::Dump qw( pp );

BEGIN { use_ok('FsDB') };

my $DIR = 'test-dir';
remove_tree( $DIR );
END { remove_tree( $DIR ) }
my $DIR2 = 'test-iter';
remove_tree( $DIR2 );
END { remove_tree( $DIR2 ) }
my $DIR3 = 'test-depth';
remove_tree( $DIR3 );
END { remove_tree( $DIR3 ) }

my %hash;
tie %hash, 'FsDB', $DIR, O_CREAT, 0640;
isa_ok( tied( %hash ), 'FsDB' ) or die tied %hash;

ok( !exists $hash{honk}, "No honk" );

my $s = $hash{honk} = "bonk";
is( $s, 'bonk', "Returned scalar" );
ok( exists $hash{honk}, "Created honk" );

is( $hash{honk}, "bonk", "Read honk" );

delete $hash{honk};
ok( !exists $hash{honk}, "No more honk" );

$hash{foo} = {};
my $f = $hash{foo};
ok( !ref $f, "Don't save refs" );

SKIP: {
    skip "Doesn't freeze", 4;
    my $d = $hash{bonk} = { hello=>1 };
    is( ref $d, 'HASH', "Returned ref" );
    ok( exists $hash{bonk}, "Created bonk" );

    is_deeply( $hash{bonk}, {hello=>1}, "Read bonk" );
    isnt( $hash{bonk}, $d, "Different data" );
}

#####
my %iter;
tie %iter, 'FsDB', {dir=>$DIR2};
isa_ok( tied( %iter ), 'FsDB' ) or die tied %iter;

is_deeply( [keys %iter], [], "No keys" );


$iter{honk} = "hello sailor";
is_deeply( [keys %iter], ['honk'], "One key" );

delete $iter{honk};
is_deeply( [keys %iter], [], "No key" );

my $key1 = "honk\nbonk";
$iter{ $key1 } = "foo";

is_deeply( [keys %iter], [$key1], "One key" );

my $key2 = "honk\n";
$iter{ $key2 } = "foo";
is_deeply( [sort keys %iter], [$key2, $key1], "two key" );

my $key3 = "honk\0";
$iter{ $key3 } = "foo";
is_deeply( [sort keys %iter], [$key3, $key2, $key1], "3 key" );

delete @iter{$key1, $key2,  $key3};


for( 1..9 ) {
    $iter{$_} = "honk";
}
$iter{0} = "zip";

is_deeply( [sort keys %iter], [0..9], "10 keys" );

delete $iter{9};
is_deeply( [sort keys %iter], [0..8], "9 keys" );


@iter{ qw( honk bonk ) } = (1) x 2;

is_deeply( [sort keys %iter], [0..8, qw( bonk honk )], "11 keys" );



#####
my %depth;
tie %depth, 'FsDB', {dir=>$DIR3, depth=>1};
ok( !exists $depth{something}, "No something" );
$depth{something} = 1;
ok( exists $depth{something}, "Yes something" );
