#!/usr/bin/perl
use strict;
use warnings;

use UI::Dialog;
use Term::ReadKey;
use Term::ANSIScreen qw(cls);

my $FileEditor = "/bin/nano";
my $Pager = "/usr/bin/less";
my $HOME = $ENV{HOME};
my $FairLandSettings = "$HOME/.EmpSettingsDir";
my $EmpireWorldToolDir = "$HOME/WolfpackEmpireCreator";
chdir $EmpireWorldToolDir;
#my $EmpireWorldToolDir = "WolfpackEmpireCreator";
my $UpdateCommand = "/usr/bin/git pull";
my $DEBUG_MODE = "off";

###################################################
# No changes below here
###################################################

my $EmpireWorldTool_ver = "0.2";

my %GameNames = ();
my %GameSeed = ();
my %GameNumCont = ();
my %GameContSize = ();
my %GameNumIsl = ();
my %GameAvgSizeIsl = ();
my %GameSpikePct = ();
my %GamePctMountian = ();
my %GameMinDistCont = ();
my %GameMinDistIslands = ();
my %GameConfFile = ();
my %file_data = ();

sub PrintDebugCommand
{
	if ($DEBUG_MODE eq "off")
	{
		return;
	}
	my $PassedString = shift;
	print "About to run:\n$PassedString\n";
	print "Press Enter To Run This:";
	my $entered = <>;
}

my $menuselection = "";

if (! -e $FairLandSettings)
{
	if (! -d $FairLandSettings)
	{
		#mkdir ("$FairLandSettings") || die("Unable to create the settings directory");
		mkdir ("$FairLandSettings");
	}
}
chdir $FairLandSettings;

sub LoadInSettings
{
	if (! -e "$FairLandSettings/oursettings")
	{
		system("touch $FairLandSettings/oursettings");
	}
	open(IN, "$FairLandSettings/oursettings") || die("ERROR: Could not open input file $FairLandSettings/oursettings");
	my $line;
	while($line = <IN>)
	{
		chomp($line);
		my @line_info = split(/\t/, $line);
		my $key_field = $line_info[0];
		
		my $line_info = \@line_info;
		for (my $i = 0; $i <= $#$line_info; $i++)
		{
			$file_data{$key_field}{$i} = $line_info->[$i];
			PrintDebugCommand("$file_data{$key_field}{$i}");
		}
	}
	close(IN);
	foreach my $key (keys %file_data)
	{
		PrintDebugCommand("ScriptKey: $key");
		$GameNames{$key} = $file_data{$key}{0};
		$GameSeed{$key} = $file_data{$key}{1};
		$GameNumCont{$key} = $file_data{$key}{2};
		$GameContSize{$key} = $file_data{$key}{3};
		$GameNumIsl{$key} = $file_data{$key}{4};
		$GameAvgSizeIsl{$key} = $file_data{$key}{5};
		$GameSpikePct{$key} = $file_data{$key}{6};
		$GamePctMountian{$key} = $file_data{$key}{7};
		$GameMinDistCont{$key} = $file_data{$key}{8};
		$GameMinDistIslands{$key} = $file_data{$key}{9};
		$GameConfFile{$key} = $file_data{$key}{10};
	}
	if ($DEBUG_MODE ne "off")
	{
		sleep (5);
	}
}

# Load in all the games created
LoadInSettings();

my $d = new UI::Dialog ( backtitle => "EmpireWorldTool v$EmpireWorldTool_ver", height => 20, width => 65, listheight => 5,
	order => [ 'ascii', 'cdialog', 'xdialog' ]);

my $windowtitle = "Welcome to EmpireWorldTool!";
my $enjoyedtitle = "We hope you enjoyed EmpireWorldTool!";
my $introtext =
"This is the EmpireWorldTool, a utility to create Empire
fairland commands for Empire operators to easily create and
store your fairland world creation settings.";

$d->msgbox( title => $windowtitle, text => $introtext );

if (($d->state() eq "ESC") || ($d->state() eq "CANCEL"))
{
	exit 0;
}

sub DoUpdate
{
	my $DesiredDir = $_[0];

	# Update desired utility
	chdir ($DesiredDir);
	PrintDebugCommand("Running $UpdateCommand in $DesiredDir\n");
	system("$UpdateCommand");
	print "Press Enter To Continue";
	my $entered = <>;
}

sub UpdateToolsMenu
{
	$menuselection = $d->menu( title => "Update Tools Menu", text => "Select one:",
                            list => [ '1', 'Update EmpireWorldTool',
                                      'q', 'Main Menu' ] );
}

sub UpdateTools
{
	while (-1)
	{
		UpdateToolsMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Update EmpireWorldTool
			DoUpdate($EmpireWorldToolDir);
		}
	}
}

# fairland command-line arguments
# fairland  [-ahioqv]  [-e configfile] [-R seed] "Number of Contenents" "Contenent Size" "Number of Islands" "Average Size of Islands" "Spike percentage def 10" "Percent of Land that is mountain" "Minimum Distance between contenents" "Minimum Distance from islands to contenents"

sub ReadInput
{
	my $CurrentString = $_[0];
	my $Prompt = $_[1];

	while (-1)
	{
		if (defined($CurrentString))
		{
			print "$Prompt (Currently: $CurrentString): ";
		}
		else
		{
			print ("$Prompt: ");
		}
		my $InputLine = <>;
		if (($InputLine eq "q") || ($InputLine eq "Q") || ($InputLine eq "quit"))
		{
			return "";
		}
		if ($InputLine ne "")
		{
			chop($InputLine);
			return $InputLine;
		}
	}
}

my $SettingsName = "";

sub WriteHashes
{
	# ZZZ
	open(my $fh, '>', "$FairLandSettings/oursettings") || die("Unable to update '$FairLandSettings/oursettings'");
my $Foo = keys %file_data;
#print "$file_data{$key}{0}\n";
print "'foo is $Foo'\n";
#my $Temp = keys %file_data;
#print "hash is '$Temp'\n";
	foreach my $key (keys %file_data)
	{
print "Dumping '$key'\n";
		print($fh "$GameNames{$key}	$GameSeed{$key}	$GameNumCont{$key}	$GameContSize{$key}	$GameNumIsl{$key}	$GameAvgSizeIsl{$key}	$GameSpikePct{$key}	$GamePctMountian{$key}	$GameMinDistCont{$key}	$GameMinDistIslands{$key}	$GameConfFile{$key}\n");
		print("$GameNames{$key}	$GameSeed{$key}	$GameNumCont{$key}	$GameContSize{$key}	$GameNumIsl{$key}	$GameAvgSizeIsl{$key}	$GameSpikePct{$key}	$GamePctMountian{$key}	$GameMinDistCont{$key}	$GameMinDistIslands{$key}	$GameConfFile{$key}\n");
	}
	close($fh);
	#LoadInSettings();
sleep (5);
}

sub Add_New_Entry
{
	system ("clear");
	print "Enter Desired Game Name: ";
	$SettingsName = <>;
	chop($SettingsName);
	PrintDebugCommand("Entered name is '$SettingsName'\n");

	if (($SettingsName eq "") || ($SettingsName eq "q") || ($SettingsName eq "Q"))
	{
		return;
	}
	$GameNames{$SettingsName} = $SettingsName;
	$GameSeed{$SettingsName} = ReadInput($GameSeed{$SettingsName}, "Game Seed - leave blank for random");
	$GameNumCont{$SettingsName} = ReadInput($GameNumCont{$SettingsName}, "Number of contenents");
	$GameContSize{$SettingsName} = ReadInput($GameContSize{$SettingsName}, "Contenent Size");
	$GameNumIsl{$SettingsName} = ReadInput($GameNumIsl{$SettingsName}, "Number of Islands");
	$GameAvgSizeIsl{$SettingsName} = ReadInput($GameAvgSizeIsl{$SettingsName}, "Average Size of Islands");
	$GameSpikePct{$SettingsName} = ReadInput($GameSpikePct{$SettingsName}, "Spike Percentage def 10");
	$GamePctMountian{$SettingsName} = ReadInput($GamePctMountian{$SettingsName}, "Percent of Land That is Mountian");
	$GameMinDistCont{$SettingsName} = ReadInput($GameMinDistCont{$SettingsName}, "Minimum Distance Between Contenents");
	$GameMinDistIslands{$SettingsName} = ReadInput($GameMinDistIslands{$SettingsName}, "Minimum Distance From Islands to Contenenta");
	$GameConfFile{$SettingsName} = ReadInput($GameConfFile{$SettingsName}, "Config file with your settings");
	# Write out hashes to disk
	WriteHashes();
}

sub List_Servers
{
	system("clear");
	print "Name | Seed | NumCont | Cont Size | NumIsl | AvgSize | SpikePct | PctMnt | MinDistCont | MinDistIsl | ConFile\n";
	foreach my $key (keys %file_data)
	{
		print "Game Name: $GameNames{$key}\n";
		my $fairland_command = "fairland -e '$GameConfFile{$key}' ";
		PrintDebugCommand("Key Field: $key");
		if ($GameSeed{$key} ne "")
		{
			$fairland_command = "$fairland_command -R '$GameSeed{$key}' ";
		}
		$fairland_command = "$fairland_command  $GameNumCont{$key} $GameContSize{$key} $GameNumIsl{$key} $GameAvgSizeIsl{$key} $GameSpikePct{$key} $GamePctMountian{$key} $GameMinDistCont{$key} $GameMinDistIslands{$key}";
		print "$fairland_command\n";
	#	print "$key | $GameSeed{$key}| $GameNumCont{$key} | $GameContSize{$key} | $GameNumIsl{$key} | $GameAvgSizeIsl{$key} | $GameSpikePct{$key} | $GamePctMountian{$key} | $GameMinDistCont{$key} | $GameMinDistIslands{$key}\n";
		print "=============================\n";
	}
	print "Press ENTER to continue:";
	my $entered = <>;
}

sub MainMenu
{
	$menuselection = $d->menu( title => "Main Menu", text => "Select one:",
                            list => [
                                      '1', 'Add Server',
                                      '2', 'List Servers',
                                      '3', 'Update EmpireWorldTool',
                                      'q', 'Quit' ] );
}

while (-1)
{
	MainMenu();
	if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "q") || ($menuselection eq "Q"))
	{
		$d->msgbox( title => $enjoyedtitle, text => "Thanks for using EmpireWorldTool..." );
		exit 0;
	}
	elsif ($menuselection eq "1")
	{
		# Add Server
		Add_New_Entry();
	}
	elsif ($menuselection eq "2")
	{
		# List Servers
		List_Servers();
	}
	elsif ($menuselection eq "3")
	{
		# Update Menu
		UpdateTools();
	}
}

exit 0;
