# Author:  Chao-Kuei Hung
# For more info, including license, please see doc/index.html

package Configurable;
# Configurable objects

use strict;
use Carp;
use vars qw(@ISA);
@ISA = qw();

require "basic.pl";

sub new {
    my ($class, %opts) = @_;
    $class = ref($class) if ref($class);
    return bless ::deep_copy(\%opts), $class;
}

my (@cfg_file_list, $init);
@cfg_file_list = ("$ENV{HOME}/.algotutor", "/etc/algotutor");
foreach $init (@cfg_file_list) {
    if (-r $init) {
	$::UserConfig = require $init;
	print STDERR "using config file $init\n";
	last;
    }
}

sub cget {
    my ($self, $opt) = @_;
    my ($CLASS) = $self;
    if (ref $self) {
	return $self->{$opt} if exists $self->{$opt};
	$CLASS = ref $self;
    }
    return $::UserConfig->{$CLASS}{$opt}
	if exists $::UserConfig->{$CLASS}{$opt};
    while (defined $CLASS) {
#print "C($opt):$CLASS -- ", join(",",keys %{ $::Config->{$CLASS} }), "\n";
	return $::Config->{$CLASS}{$opt}
	    if defined $::Config->{$CLASS}{$opt};
	$CLASS = ::parent_class($CLASS);
    }
}

sub get_all_opts {
    my ($self) = @_;
    my ($CLASS) = $self;
    $CLASS = ref $self if ref $self;
    my (@ANCESTORS) = ();
    while ($CLASS) {
	push @ANCESTORS, $CLASS;
	$CLASS = ::parent_class($CLASS);
    }
    my (%opts) = ();
    while (@ANCESTORS) {
	%opts = (%opts, %{ ::deep_copy($::Config->{pop @ANCESTORS}) } );
    }
    if (ref $self) {
	my (@k) = grep { /^-\w+$/ } keys %$self;
	my ($highest) = { map { $_=>$self->{$_} } @k };
	%opts = (%opts, %{ ::deep_copy($highest) });
    }
    return %opts;
}

$::Config->{Configurable} = {
};

1;

