package Orchard::YamlConfig;

use strict;
use warnings;

use base 'Class::Accessor';

use YAML::Syck;
use File::Basename;
use Class::Inspector;

sub get_config {
    my $package      = shift;
    my $mk_accessors = shift || 'TRUE';
    my $self_path    = Class::Inspector->resolved_filename($package);
    my $conf_name    = File::Basename::basename( $self_path, '.pm' );
    my $yaml_path    = File::Basename::dirname($self_path) . '/' . $conf_name . '.yml';
    _get_config_( $yaml_path, $mk_accessors );
}

sub get_config_from_file {
    my $filepath = shift;
    my $mk_accessors = shift || 'TRUE';
    _get_config_( $filepath, $mk_accessors );
}

sub _get_config_ {
    my $yaml_path    = shift;
    my $mk_accessors = shift || 'TRUE';
    my $config       = YAML::Syck::LoadFile($yaml_path);

    return $config unless $mk_accessors eq 'TRUE';

    for my $conf ( keys %{$config} ) {
        __PACKAGE__->mk_accessors( ($conf) );
    }
    my $self = bless $config, __PACKAGE__;
    $self->add( 'file', $yaml_path );
    $self;
}

sub getkey {
    my $self = shift;
    my $key  = shift;
    $self->$key;
}

sub add {
    my $self = shift;
    my $meth = shift;
    my $data = shift;
    __PACKAGE__->mk_ro_accessors( ($meth) );
    $self->{$meth} = $data;
}

1;
