# This file is part of "KarmaLab.net Perl Library".
#    Copyright 2005, Yoran Brault
#    eMail: yoran.brault@bad_karma-lab.net (remove "bad_" before sending)
#    Site : http://artisan.karma-lab.net
#
# "KarmaLab.net Perl Library" is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# "KarmaLab.net Perl Library" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with "KarmaLab.net Perl Library"; if not, write to the Free
# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA, or see the FSF site: http://www.fsf.org.

package Settings::Simple;

use strict;
use warnings;

use base "Config::Simple";
use Logging::LoggerManager;

sub new {
    my $self =shift;
    my $fileName=shift;
    $self=$self->SUPER::new($fileName);
    if (!defined $self) {
         Logging::LoggerManager::Instance->logger(__PACKAGE__)->severe("Unable to load %s",$fileName);
        return undef;
    }
    $self->{filename}=$fileName;
    return $self;
}

sub logger {
    my $self = shift;
    if (!defined $self->{logger}) {
        $self->{logger} = Logging::LoggerManager::Instance->logger(__PACKAGE__);
    }
    return $self->{logger};
}

sub inject {
    my $self   = shift;
    my $object = shift;
    my $classname=ref($object);
    $self->logger->debug("Injecting settings to " . $classname);
    my $values = $self->SUPER::param( -block => $classname );
    my @keys=keys(%$values);
    if (scalar(@keys)==0) {
        $self->logger->severe("Missing section [%s] in %s",$classname, $self->{filename});
        return 1;
    }
    foreach my $key ( @keys ) {
        my $value=$$values{$key};
        $self->logger->debug("$value -> $classname->\{$key\}");
        if (ref($value) eq 'ARRAY') {
            my @list = @{$value};
            foreach (@list) {
                $self->logger->debug(" - $_");
            }
            $object->$key( @{$value} );
        } else {
            $object->$key( $value );
        }
    }
    return 0;
}

sub getValue {
    my $self    = shift;
    my $section = shift;
    my $name    = shift;
    my $default = shift;

    my $value = $self->SUPER::param($section.".".$name);
    if ( !defined $value && defined $default) {
        return $default;
    }
    return $value;
}

1;
