#!/usr/bin/perl -w

use Test::More tests => 7;
use Mac::Finder::DSStore;
use Mac::Finder::DSStore::BuddyAllocator;
use IO::File;
use File::Temp qw( tempfile );

#
# This is a simple test that reads in a file actually generated by
# the Finder and makes sure the records are as expected.
#
# The $testpoint hook is used to do some extra consistency/roundtrip
# tests.
#

sub test_more_hook {
    my($l, $r) = @_;
    my(undef, $file, $line) = caller;
    $file =~ s/^.*\///;
    is_deeply($_[0], $_[1], "testpoint at $file:$line");
}
$Mac::Finder::DSStore::testpoint = \&test_more_hook;

$fn = 't/store1';

# Slurp in the records. This will also invoke the testpoint once.
$store = Mac::Finder::DSStore::BuddyAllocator->open(new IO::File $fn, '<');
@recs = Mac::Finder::DSStore::getDSDBEntries($store);
$store->close;

# Make sure that the actual records we got match what we think
# we should get.
# (The actual records will be blessed into the DSStore::Entry pkg,
# but is_deeply() is documented not to care about that.)
@expected = (
    [ "another file",  "Iloc", "blob",
                   "\0\0\0O\0\0\0008\377\377\377\377\377\377\0\0"  ],
    [ "another file",  "cmmt", "ustr",
                   "I am a file comment." ],
    [ "Filename",      "Iloc",  "blob",
                   "\0\0\0R\0\0\0s\377\377\377\377\377\377\0\0"    ],
    [ "untitled folder",     "BKGD",  "blob",
                   "DefB\277\377\362x\1\200.\264"  ],
    [ "untitled folder",     "ICVO",  "bool",  1 ],
    [ "untitled folder",     "Iloc",  "blob",
                   "\0\0\0V\0\0\0\261\377\377\377\377\377\377\0\0"  ],
    [ "untitled folder",     "icgo",  "blob",
                   "\0\0\0\0\0\0\0\4"  ],
    [ "untitled folder",     "icvo",  "blob",
                   "icv4\0000nonebotm\0\0\0\0\0\0\0\0\0\4\0\0"   ],
    [ "untitled folder",     "icvt",  "shor",  13  ],
             );
is_deeply(\@recs, \@expected, "File contents OK");


# Make sure that our comparison/ordering function matches what's in the file.
$inorder = 1;
foreach $n (1 .. $#recs) {
    $inorder = 0 unless $recs[$n-1]->cmp($recs[$n]) == -1;
    $inorder = 0 unless $recs[$n]->cmp($recs[$n-1]) == 1;
}
ok($inorder, 'Record ordering function');


# Write it to a temporary file. This will invoke the testpoint once.
my(undef, $filename) = tempfile();
my($wrote) = Mac::Finder::DSStore::writeDSDBEntries($filename, @recs);
ok($wrote && ref $wrote, '&writeDSDBEntries');
$wrote->close;
undef $wrote;

# Read back from the temporary file. This will invoke the testpoint
# for a third time.
my($reread) = Mac::Finder::DSStore::BuddyAllocator->open(new IO::File $filename, '<');
@rerecs = Mac::Finder::DSStore::getDSDBEntries($reread);
$reread->close;

# Make sure the round trip didn't alter the records.
is_deeply(\@recs, \@rerecs, 'Round-trip through temporary file');



