# Quest, a computer role playing game system
# Copyright (C) 2002 Willem Robert van Hage, details in the COPYING file.

package text_io;

use strict;
use xml;
use io;
use player;

my $pl = player::new;
my %color = (
	"default" => "\033[0m",		"bold"    => "\033[1m",
	"blue"    => "\033[0;34m",	"red"     => "\033[0;31m",
	"cyan"    => "\033[0;36m",
);

sub init {
	my ($host,$port,$col) = @_;
	unless ($col) { $color{$_} = "" foreach keys %color }
	meta::init($host,$port,$pl);
	io::init($pl);
 	describe($pl->{location}); prompt(); print $color{bold};
 	while(<>) {
		print $color{default};
 		next unless /\w+/; last if /quit/; chomp; print "\n";
		inventory(), prompt(), next if /inv(entory)?\W*$/;
		look(), prompt(), next if /look/;
 		display(io::command($_));
 		describe($pl->{location}); prompt(); print $color{bold};
 	}
}

sub prompt { print "\n", $color{bold}, "> ", $color{default} }
sub look { describe($pl->{location}) } # extend to include looking at items

sub display { 
	foreach (split("\n",shift)) {
		if (/type=\"display\"/) {
			s/^.*text=\"(.*)\".*$/$1/; print $_, "\n" 
		} elsif (/type=\"error\"/) {
			s/^.*info=\"(.*)\".*$/$1/; 
			print $color{red},$_,$color{default},"\n" 
		}
	}
}

sub item { # display
	my ($i,$d) = @_; 
	return "\t" x $d .  $i->{description} . 
		" (" . $color{cyan} . $i->{name}. $color{default} . ")\n" 
}

sub describe {
	my $rm = shift;
	return unless $rm;
	print "_"x78,"\n",$color{blue},$rm->{description},$color{default},"\n\n";
	if (scalar keys %{$rm->{door}}) {
		print "doors:\n";
		print item($rm->{door}->{$_},1) foreach keys %{$rm->{door}}
	}
	if (scalar keys %{$rm->{object}}) {
		print "items:\n";
		print item($rm->{object}->{$_},1) foreach keys %{$rm->{object}}
	}
}

sub inventory {
	if (scalar keys %{$pl->{inventory}}) {
		print "inventory:\n";
		print item(player::item($pl,$_),1) foreach keys %{$pl->{inventory}}
	} else { print "you don't carry anything\n" }
}

1;

