# $Id: config.pl,v 1.1.1.1 2005/11/04 09:07:03 khlut Exp $
# Work with config file
#
#Copyright 2005 Elphel, Inc.
#
#This file is part of GenReS.
#
#    GenReS is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    GenReS 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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with GenReS; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

sub load_config
{
    local *CFG;
  return unless open( CFG, '<', $conffile );

    while(<CFG>) {
        s/\n//;
	s/#.*//;
	my($k,$v)=split / *= */, $_, 2;
	$cfg{$k}[0]=$v if($k ne "");
    }
    close(CFG);
}
sub save_config
{
    local *CFG;
    my $dir=$conffile;
    $dir=~s|/[^/]*$||;
    system("mkdir -p $dir") unless -d $dir;
    open( CFG, '>', $conffile );
    foreach(keys(%cfg)) {
	print CFG "# $cfg{$_}[2]\n";
	for( split "\n", $cfg{$_}[3] ) {
	    print CFG "#   $_\n";
	}
	print CFG "$_=$cfg{$_}[0]\n";
    }
    close(CFG);
}
sub file_dialog
{
    use Gtk2 -init;

    my $dlg;
    my @wdg;
    for(@_) {
      goto $cfg{$_}[1];
      file:
        $dlg = Gtk2::FileSelection->new($cfg{$_}[2]);
	$dlg->set_filename($cfg{$_}[0]);
	$dlg->main_vbox->pack_end(Gtk2::Label->new($cfg{$_}[3]), 0,0,0);
	my $text=Gtk2::Label->new("You may change this parameters editing file\n\"$conffile\"");
	$text->set_line_wrap(1); $text->set_justify('center');
	$dlg->main_vbox->pack_start($text,0,0,10);
	push @wdg, $dlg;
      next;
      checkbox:
        my $cb = Gtk2::CheckButton->new($cfg{$_}[2]);
	$cb->set_active($cfg{$_}[0]);
	$dlg->main_vbox->pack_start($cb,0,0,0);
	push @wdg, $cb;
      next;
      text:
	my $w=Gtk2::Entry->new;
	my $hbox=Gtk2::HBox->new;
	$w->set_text($cfg{$_}[0]);
	$hbox->pack_start(Gtk2::Label->new($cfg{$_}[2]),0,1,0);
	$hbox->pack_start($w,1,1,0);
	$dlg->main_vbox->pack_start($hbox,0,0,10);
	push @wdg, $w;
      next;
    }
    $dlg->show_all();
    my $res;
    if($res = $dlg->run eq 'ok') { for(@_) {
      goto $cfg{$_}[1];
      file:
	$cfg{$_}[0]=shift(@wdg)->get_filename;
      next;
      checkbox:
	$cfg{$_}[0]=0+shift(@wdg)->get_active;
      next;
      text:
	$cfg{$_}[0]=shift(@wdg)->get_text;
      next;    
    }}
    $dlg->destroy;
    Gtk2::Gdk->flush();
    $res && save_config();
    return $res;
}

1;
