package LATMOS::Accounts;

use 5.010000;
use strict;
use warnings;
use base qw(Config::IniFiles);
use LATMOS::Accounts::Bases;

our $VERSION = (q$Rev$ =~ /^Rev: (\d+) /)[0];

sub new {
    my ($class, $config) = @_;

    $config ||= '/etc/latmos-account.ini';

    my $self = Config::IniFiles->new(
        -file => $config
    );

    bless($self, $class)
}

sub base {
    my ($self, $section) = @_;
    # this method perform a cache
    $self->{_bases}{$section} and return $self->{_bases}{$section};
    $self->load_base($section) ? $self->{_bases}{$section} : undef;
}

sub default_base {
    my ($self) = @_;
    my $default = $self->default_base_name or return;
    $self->base($default);
}

# load or a if need base
sub load_base {
    my ($self, $section) = @_;
    return ($self->{_bases}{$section} ||= $self->_load_base($section))
        ? 1
        : 0;
}

# do the bad work
sub _load_base {
    my ($self, $section) = @_;
    my $type = $self->val($section, 'type') or return;
    my %params = map { $_ => ($self->val($section, $_)) } $self->Parameters($section);
    my $base = LATMOS::Accounts::Bases->new($type, %params, label => $section);
    $base->load or return;
    $base;
}

sub default_base_name {
    my ($self) = @_;
    $self->val('_default_', 'base', ($self->list_bases)[0]);
}

sub list_bases {
    my ($self) = @_;
    grep {
        !m/^_.*_$/
    } $self->Sections
}

sub load_all_base {
    my ($self) = @_;
    foreach ($self->list_bases) {
        $self->load_base($_) or do {
            warn "Cannot load base $_\n";
            return 0;
        };
    }
    1;
}

sub config_sync_base {
    my ($self, $from) = @_;
    return split(/ /, $self->val($from, 'push', ''));
} 

1;

__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

LATMOS::Accounts - Perl extension for blah blah blah

=head1 SYNOPSIS

  use LATMOS::Accounts;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for LATMOS::Accounts, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head2 EXPORT

None by default.



=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

Thauvin Olivier, E<lt>olivier.thauvin@latmosipsl.frE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 by Thauvin Olivier

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.


=cut
