package tests::TestStoreFixture;

use strict;

use Cwd qw/realpath/;

use File::Path qw/mkpath rmtree/;
use File::Basename qw/dirname/;

use POSIX qw/setlocale LC_MESSAGES/;

use Locale::Messages qw/bindtextdomain bind_textdomain_codeset/;

use Lire::Config::SpecParser;
use Lire::Config::TypeSpec;
use Lire::DlfStore;
use Lire::Utils qw/tempdir/;

#
# Fixture which initialize for TestCase which requires the use
# of test_store.
#
# It also makes available the test schemas.
#
# The test_store will be accessible through the 'store' attribute.
#
sub init {
    my $self = $_[0];

    $self->{'testdir'} = realpath( dirname(__FILE__) );
    $self->{'schemasdir'} = $self->{'testdir'} . "/schemas";
    $self->{'store_tar'} = $self->{'testdir'} . "/data/test_store.tar";

    return;
}

sub init_i18n {
    my $self = $_[0];

    $self->{'localedir'} = tempdir( __PACKAGE__ . "XXXXXX", CLEANUP => 1 );
    mkpath( [ $self->{'localedir'} . "/fr/LC_MESSAGES" ], 0, 0755 );
    system( "cp $self->{'testdir'}/po/fr.mo $self->{'localedir'}/fr/LC_MESSAGES/lire-test.mo" );

    return;
}

sub set_up_test_schema {
    my $self = $_[0];

    $self->{'cfg'}{'lr_schemas_path'} = [ $self->{'schemasdir'},
                                          "$self->{'testdir'}/../../schemas"
                                        ];
    return;
}

sub set_up_test_store {
    my ( $self, $open ) = @_;

    $open = 1 unless defined $open;

    $self->set_up_test_schema();

    $self->{'tmpdir'} = tempdir( __PACKAGE__ . "XXXXXX", CLEANUP => 1 );

    system( "cd $self->{'tmpdir'}; tar xf $self->{'store_tar'}" );
    die "tar failed: $?" if $?;

    # Lire::DlfStore::open calls Lire::Config->config_spec()
    $self->{'cfg'}{'_lr_config_spec'} = $self->lire_default_config_spec()
      unless ( $self->{'cfg'}{'_lr_config_spec'} 
               && $self->{'cfg'}{'_lr_config_spec'}->has_component( 'streams_config' ) );
    $self->{'store_path'} = "$self->{'tmpdir'}/test_store";
    $self->{'store'} = Lire::DlfStore->open( $self->{'store_path'} )
      if $open;

    return;
}

sub set_up_locale {
    my $self = $_[0];

    $self->{'old_localedir'} = bindtextdomain( 'lire-test' );
    bindtextdomain( 'lire-test', $self->{'localedir'} );
    bind_textdomain_codeset( 'lire-test', 'iso-8859-1' );

    return;
}

sub tear_down_locale {
    my $self = $_[0];

    bindtextdomain( 'lire-test', $self->{'old_localedir'} );

    return;
}

sub set_locale {
    my ( $self, $locale ) = @_;

    setlocale( LC_MESSAGES, $locale );
}

sub tear_down_test_store {
    my $self = $_[0];
    $self->{'store'}->close();
    rmtree( $self->{'tmpdir'} );

    return;
}

1;


syntax highlighted by Code2HTML, v. 0.9.1