#!/usr/bin/perl -w
use strict;
use lib $ENV{ 'MAIN_CONF'}  ;
use main_config ;

# Tk libraries #
use Tk;
use Tk::Balloon;
use Tk::LabFrame;
use Tk::BrowseEntry;

### CONFIG ###
# arrayes and hashes #
my @variables = ();
my %commands = () ;
my %range = ();
my %value = ();
my %description = ();
my %defaults =  ();
my %entry_text = ();
my %max = ();
my %min = ();
my $command;

my @in_lines = ();
my @temp_commands = ();
my @defaults = ();

# variables #
my $key;
my $i = 0; 
my $j = 0;
my $num_of_var = 0;
my $temp_comm;
my $temp_var;
my $temp_def;
my $count = 0;
my @a_range = ();

# Tk variables #
my %Tk_variables = ();
my %Tk_values = ();
my %Tk_help = ();
my %Tk_frames = ();
my %Tk_frame1 = ();
my %Tk_frame2 = ();
my %Tk_scrollbar = ();

my $conf_file ;
if ( -f "main_config.data" ) {    
    $conf_file = "main_config.data" ; 
    print "File found!\n";
} else {    
    $conf_file = join ('', $ENV{"MAIN_CONF"}, "main_config.data" ) ; 
}

my %my_main = main_config::read_main_config_file ( $conf_file ) ; 

my $file = join ('', $ENV{"MAIN_CONF"}, "$ARGV[0]" ) ;

### READ DEFAULTS ###

open (FILE, "$file") || die "Sorry, I couldn't open $file: $!";
while (<FILE>) {
    if (/exists/) {
	push (@in_lines, $_);    
    }
}
close (FILE);

foreach (@in_lines) {
    # print "$_\n";
    ($temp_var) = /\{\"(.+?)\"\}/;
    push (@variables, $temp_var);
    ($temp_def) = /, (.*?) \)/;
    if ($temp_def =~ /\"/) {
	($temp_def) = ($temp_def =~ /\"(.*?)\"/);
    }
    $defaults {$temp_var} = $temp_def;
    # print "$temp_var = $temp_def\n";
}

foreach (@variables) {
    if ( !exists($my_main{$_}) ) { 
	push ( @{$my_main{$_}}, $defaults{$_}) ; 
    }
    # print "$my_main{$_}[0]\n";
}

### OPEN CLOSE FILE ###
@in_lines = ();

open (FILE, "$file") || die "Sorry, I couldn't open $file: $!";
while (<FILE>) {
    if (/print << "END_OF_TEXT"/) {
	while (<FILE>) {
	    if (/END_OF_TEXT/) {
		goto END;
	    }
	    push (@in_lines, $_);    
	}
    }
}
END:
close (FILE);

### START EXTRACTING DATA ###

shift (@in_lines);
pop (@in_lines);

foreach (@in_lines) {
    # print "$_\n";
    chomp ($_);
    if ($count == 0) {
	$temp_comm = $_;
    } else {
	
	if (/^[ ]*-/) {
	    push (@temp_commands, $temp_comm);
	    $temp_comm = $_;
	} else {
	    $temp_comm = "$temp_comm"." "."$_";
	}
    }
    $count = 1;
}
push (@temp_commands, $temp_comm);

# foreach (@temp_commands) {
#     print "$_\n";
# }

foreach $temp_var (@variables) {
    foreach (@temp_commands) {
	if (/$temp_var/) {
	    ($commands{$temp_var}) = /\|\-\-(.+?)\)/;
	    ($description{$temp_var}) = /\)[ ]*(.+?)\[/;
	    $description{$temp_var} =~ s/= //;
	    ($range{$temp_var}) = /\[([-0-9.]+?\-[^\]]+)/;
	    if ($range{$temp_var} eq "") {
		($range{$temp_var}) = /\[(.+[\/?][^\]]+)/;
	    }
	    if ($range{$temp_var} eq "") {
		$range{$temp_var} = 0;
	    }
	}
    }
    $value{$temp_var} = $my_main{$temp_var}[0];
}

$num_of_var = scalar(@variables);

for ($i = 0; $i < $num_of_var; $i++) {
    $_ = $variables[$i];
    if ($commands{$_} && $commands{$variables[$i+1]}) {
	
	if ($commands{$_} eq $commands{$variables[$i+1]}) {
	    print "$_ - $variables[$i+1]\n";
	    print "\tValue: $value{$_} - $value{$variables[$i+1]}\n";
	    print "\tDescription: $description{$_}\n"; 
	    print "\tDefault value of $defaults{$_} - $defaults{$variables[$i+1]}\n";
	    print "\tCommand --$commands{$_}\n";
	    if ($range{$_} ne 0) {
		print "\tRange [$range{$_}]\n";
	    } else {
		print "\tNo defined range.\n";
	    }
	    $i++;
	} else {
	    print "$_\n";
	    print "\tValue = $value{$_}\n";
	    print "\tDescription: $description{$_}\n"; 
	    print "\tDefault value of $defaults{$_}\n";
	    print "\tCommand --$commands{$_}\n";
	    if ($range{$_} ne 0) {
		print "\tRange [$range{$_}]\n";
	    } else {
		print "\tNo defined range.\n";
	    }
	}
    } elsif ($commands{$_}) {
	print "$_\n";
	print "\tValue = $value{$_}\n";    
	print "\tDescription: $description{$_}\n"; 
	print "\tDefault value of $defaults{$_}\n";
	print "\tCommand --$commands{$_}\n";
	if ($range{$_} ne 0) {
	    print "\tRange [$range{$_}]\n";
	} else {
	    print "\tNo defined range.\n";
	}
    }
}

##############################################################################
############ TK PART ###### TK PART ############ TK PART #####################
##############################################################################

#main window
my $mw = MainWindow -> new;
$mw -> title ("Perl/Tk interface for MAIN");

#frames
my $lf = $mw -> LabFrame (-label => "$ARGV[0]", -labelside => 'acrosstop', -foreground=> 'darkred') -> pack;

my $main_frame = $lf -> Frame (-relief => 'flat') -> pack (-side => 'top', -fill => 'both');

my $button_frame = $lf -> Frame (-relief => 'groove') -> pack (-side => 'bottom', -fill => 'both');

my $comment_frame = $mw -> Frame (-relief => 'groove') -> pack (-side => 'bottom', -fill => 'both', -expand => 1);


#buttons
my $comment = $comment_frame -> Label (-text => "GUI for MAIN powered by perl/Tk", relief => 'groove', -foreground => 'darkred', -justify => 'left', -height => '2') -> pack (-side => 'left', -anchor => 'w', -fill => 'x', -expand => 1);

my $doit_b = $button_frame -> Button (-text => "DOIT", 
				      -command => sub {doit()}) -> pack (-side => 'left', -fill => 'x', -expand => 1);

my $default_b = $button_frame -> Button (-text => "Use defaults", 
				      -command => sub {defaults()}) -> pack (-side => 'left', -fill => 'x', -expand => 1);

my $dismiss_b = $button_frame -> Button (-text => "Exit", 
					-command => sub {exit;}) -> pack (-side => 'left', -fill => 'x', -expand => 1);

my $buttonhelp = $button_frame -> Balloon (-bg => 'white',
					   -foreground => 'black');

$buttonhelp -> attach ($dismiss_b, -msg => "Quit application");
$buttonhelp -> attach ($doit_b, -msg => "Run application");
$buttonhelp -> attach ($default_b, -msg => "Select default setings");

#variables
$num_of_var = scalar(@variables);

for ($i = 0; $i < $num_of_var; $i++) {
    $_ = $variables[$i];
    if ($commands{$_}) {
	if ($range{$_} =~ /-/) {
	    $min{$_}, $max{$_} = split /-/, $range{$_};  
	}

	$Tk_frames{$_} = $main_frame -> Frame (-relief => 'groove') -> pack (-side => 'top', -fill => 'both');


######### ON OFF ##########	
	if ($range{$_} =~ /ON\/OFF/) {
	    $Tk_variables{$_} = $Tk_frames{$_} -> Label (-text => "$_", relief => 'groove') -> pack (-side => 'left', -anchor => 'w', -fill => 'x');
	    
	    # $Tk_help{$_} = $Tk_frames{$_} -> Button (-bitmap => 'info', -relief => 'ridge') -> pack (-side => 'right', -anchor => 'e');
	    $Tk_help{$_} = $Tk_frames{$_} -> Button (-text => "?", -relief => 'ridge', -foreground => 'darkred') -> pack (-side => 'right', -anchor => 'e');
	    
	    $Tk_values{$_} = $Tk_frames{$_} -> Radiobutton (-text => 'OFF', -value => 'OFF', relief => 'flat', -variable => \$value{$_}) -> pack (-side => 'right', -anchor => 'e');
	    
	    $Tk_frames{$_} -> Radiobutton (-text => 'ON', -value => 'ON', relief => 'flat', -variable => \$value{$_}) -> pack (-side => 'right', -anchor => 'e');

#### MULTIPLE CHOICES  ###########	    
	} elsif ($range{$_} =~ /\//) {
	    $Tk_variables{$_} = $Tk_frames{$_} -> Label (-text => "$_", relief => 'groove') -> pack (-side => 'left', -anchor => 'w', -fill => 'x');
	    
	    # $Tk_help{$_} = $Tk_frames{$_} -> Button (-bitmap => 'info', -relief => 'ridge') -> pack (-side => 'right', -anchor => 'e');
	    $Tk_help{$_} = $Tk_frames{$_} -> Button (-text => "?", -relief => 'ridge', -foreground => 'darkred') -> pack (-side => 'right', -anchor => 'e');
	    
	    @a_range = split /\//, $range{$_};

	    $Tk_values{$_} = $Tk_frames{$_} -> BrowseEntry (-variable => \$value{$_}, -state => 'readonly') -> pack (-side => 'right', -anchor => 'w');
	    foreach $key (@a_range) {
		    $Tk_values{$_} -> insert ('end', $key);
	    }
	    @a_range = ();

########## CONNECTED VARIABLES  ############
#	 } elsif ($commands{$_} && $commands{$variables[$i+1]}) {
#	     
#	     if ($commands{$_} eq $commands{$variables[$i+1]}) {
#
#		 $Tk_variables{$_} = $Tk_frames{$_} -> Label (-text => "$_", relief => 'groove') -> pack (-side => 'left', -anchor => 'w', -fill => 'x');
#		 
#		 $Tk_help{$_} = $Tk_frames{$_} -> Button (-bitmap => 'info', -relief => 'ridge') -> pack (-side => 'right', -anchor => 'e');
#		 
#		 $Tk_values{$_} = $Tk_frames{$_} -> Radiobutton (-text => 'OFF', -value => 'OFF', relief => 'flat', -variable => \$value{$_}) -> pack (-side => 'right', -anchor => 'e');
#		 
#		 $Tk_frames{$_} -> Radiobutton (-text => 'ON', -value => 'ON', relief => 'flat', -variable => \$value{$_}) -> pack (-side => 'right', -anchor => 'e');
#
#		 if ($range{$_} ne 0) {
#		     print "\tRange [$range{$_}]\n";
#		 } else {
#		     print "\tNo defined range.\n";
#		 }
#
#		 $i++;
#	     } else {
#		 $Tk_variables{$_} = $Tk_frames{$_} -> Label (-text => "$_", relief => 'groove') -> pack (-side => 'left', -anchor => 'w', -fill => 'x');
#		 
#		 $Tk_help{$_} = $Tk_frames{$_} -> Button (-bitmap => 'info', -relief => 'ridge') -> pack (-side => 'right', -anchor => 'e');
#		 
#		 $Tk_values{$_} = $Tk_frames{$_} -> Entry (-textvariable => \$value{$_}, -relief => 'flat', -background => 'white', -foreground => 'black', -width => 8, -justify => 'right') -> pack (-side => 'right', -anchor => 'e');
#	     }
#	     
	} else {	    
	    $Tk_variables{$_} = $Tk_frames{$_} -> Label (-text => "$_", relief => 'groove') -> pack (-side => 'left', -anchor => 'w', -fill => 'x');
	    
	    # $Tk_help{$_} = $Tk_frames{$_} -> Button (-bitmap => 'info', -relief => 'ridge') -> pack (-side => 'right', -anchor => 'e');
	    $Tk_help{$_} = $Tk_frames{$_} -> Button (-text => "?", -relief => 'ridge', -foreground => 'darkred') -> pack (-side => 'right', -anchor => 'e');
	    	    
	    $Tk_values{$_} = $Tk_frames{$_} -> Entry (-textvariable => \$value{$_}, -relief => 'flat', -background => 'white', -foreground => 'black', -width => 8, -justify => 'right') -> pack (-side => 'right', -anchor => 'e');
	}
	
	$buttonhelp -> attach ($Tk_help{$_}, -msg => "$description{$_}");
	if ($range{$_} ne 0) {
	} else {
	}
    }
}


################
### COMMANDS ###
################

MainLoop;


sub
doit () {
    for ($i = 0; $i < $num_of_var; $i++) {
	$_ = $variables[$i];
	if ($commands{$_}) {
	    
	    print "R $range{$_}\n";
	    print "$value{$_}\n";
	    if ($range{$_} =~ /ON\/OFF/) {
		print "$value{$_}\n";
	    } elsif ($range{$_} =~ /\//) {
		print "$value{$_}\n";
	    } else {
		$value{$_} = $Tk_values{$_} -> get();
		print "$value{$_}\n";
	    }
	}
	END_LIST:	    
    }

    for ($i = 0; $i < $num_of_var; $i++) {
	$_ = $variables[$i];
	if ($commands{$_}) {

 	    print "--$commands{$_} $value{$_}\n";
	    $command = $command."--$commands{$_} $value{$_} ";
	}
    }
### END - write to save ###
  main_config::write_main_config_file ( $conf_file, %my_main ) ; 

    print "$ARGV[0] $command\n";
    # system ("$ARGV[0] $command");
    exit;
}


sub
defaults () {
    for ($i = 0; $i < $num_of_var; $i++) {
	$_ = $variables[$i];
	if ($commands{$_}) {
	    
	    $value{$_} = $defaults{$_};
	}
    }

    for ($i = 0; $i < $num_of_var; $i++) {
	$_ = $variables[$i];
	if ($commands{$_}) {
	    
	    print "--$commands{$_} $value{$_}\n";
	}
    }


}
