package XChatPerlEval;

use strict;
use vars qw( $dir $cfname %conf );

$dir = IRC::get_info(4);
$cfname = "perleval";
%conf = ();

IRC::register("PerlEval","v0.02","XChatPerlEval::save","");
IRC::add_command_handler("perl","XChatPerlEval::eval");

sub _save_stringify {
    my ( $names, $name, $value ) = @_;
    return join( ' ', @$names, $name ) . ' = ' . $value . "\n"
	unless ref $value;
    my $result = '';
    my @names = ( @$names, $name );
    return 
	map( { _save_stringify( \@names, $_, $value->{$_} ) }
	     sort keys %$value );
}

sub save {
  my $filename = shift || $cfname;
  my $conf = shift || \%conf;
  my $caller = shift || 'PerlEval';
  $filename = "$dir/$filename.conf";
  open F, ">$filename" 
      or return;
  my $i = 0;
  foreach( sort keys %$conf ) {
      print F _save_stringify( [], $_, $conf->{$_} );
      $i++;
  }
  close F;
  IRC::print( "$caller saved $i groups of settings into $filename\n" );
}

sub load {
  my $filename = shift || $cfname;
  my $conf = shift || \%conf;
  my $caller = shift || 'PerlEval';
  $filename = "$dir/$filename.conf";
  if( ! open F, $filename ) {
    IRC::print("$caller missing $filename\n");
    return;
  }
  my $i=0;
  while( <F> ) {
      chomp;
      my ( $key, $value ) =
	  /^(.*?)\s*=\s*(.*)\s*$/ or next;
      my @key = split( /\s+/, $key );
      $key = pop @key;
      my $hash = $conf;
      foreach( @key ) {
	  $hash = $hash->{$_} ||= {};
      }
      $hash->{$key} = $value;
      $i++;
  }
  close F;
  my $j = keys(%$conf);
  IRC::print("$caller loads $i settings in $j groups from $filename\n");
  return $conf;
}

sub eval {
  my @result;
  eval("\@result=@_");
  IRC::print( "Eval: $@" ) if $@;
  IRC::print( join(' ',@result) ) if @result;
  return 1;
}

load();

1;
