#!/usr/bin/perl


use strict;
use warnings;

use XML::Simple;
use File::Copy;
use Games::PerlWar;


# TODO: add color entry for players and default colors
# TODO: add more of those
my @colors = ( 'pink', 'lightblue', 'yellow' );

my $game_name = shift || "game";
my $game_dir = "./$game_name";

print "creating game directories $game_dir.. ";

mkdir $game_dir or die "couldn't create directory $game_dir: $!\n";
chdir $game_dir or die "can't chdir to $game_dir: $!\n";


mkdir "history" or die "couldn't create directory history:$!\n";

mkdir 'mobil' or die "couldn't create directory mobil:$!\n";

my ( $location ) = grep -d "$_/Games/PerlWar/web", @INC or die "no installation of PerlWar found\n";

print "found PerlWar at $location\n";

$location = "$location/Games/PerlWar/web";

copy( "$location/htaccess", ".htaccess" ) or die "coudn't copy .htaccess: $!\n";
for( qw/ submit.epl perlwar.ico upload.epl upload.html/ )
{
	copy( "$location/$_", $_ ) or die "coudn't copy $_: $!\n";
}
for( qw/ include_config.xps  iteration2html.xps configuration.xps/ )
{
	copy( "$location/stylesheets/$_", $_ ) or die "coudn't copy $_: $!\n";	
}


print "\n\ngame configuration\n";
my %conf;

$conf{gameStatus} = 'ongoing';

my $input;
print "game title [$game_name]: ";
chomp( $input = <> );

$game_name = $input || $game_name;

$conf{title} = $game_name;

print "Size of the Array [100]: ";
chomp( $input = <> );
$conf{theArraySize} = $input || 100;

print "game length (0 = open-ended game) [100]: ";
chomp( $input = <> );
$conf{gameLength} = length($input) ? $input : 100;

$conf{currentIteration} = 0;

print "snippet max. length [100]: ";
chomp( $input = <> );
$conf{snippetMaxLength} = $input || 100;

print "mambo game (0=no, any positive integer is taken as the decrement)[0]: ";
chomp( $input = <> );
$conf{mamboDecrement} = $input;

my %players;
$conf{player} = \%players;

while(1)
{
	print "enter a player (name password [color]), or nothing if done: ";
	my( $name, $password, $color ) = split ' ', <> or last;
	$color ||= shift @colors;
		
	$players{ $name } = { password => $password, color => $color };
}

print "notes (empty line to terminate):\n";
$conf{note} .= $_ while ($_ = <>) ne "\n";

print "saving configuration..\n";

Games::PerlWar::saveConfiguration( %conf );

print "creating round 0.. \n";

for my $filename ( qw/ round_current.xml round_00000.xml / )
{
	my $fh;
	open $fh, ">$filename" or die "can't create file $game_dir/$filename: $!\n";
	print $fh "<round id='0'><theArray>\n";
	print $fh "<slot id='$_'><owner></owner><code></code></slot>\n" for 0..$conf{theArraySize}-1;
	print $fh "</theArray><log/></round>";
	close $fh;
}

print "\ngame $game_name created\n";

exit;
