#!/usr/bin/perl -w

# Fake armoury replacement that actually works

die "must specify name" unless $ARGV[0];
my $CHARNAME = $ARGV[0];

$CHARNAME =~ s/.html$//;

my $charfile = "$CHARNAME.char.xhtml";

#my $USER_AGENT="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1.";
my $USER_AGENT="Firefox/2.0";

if(! -e $charfile)
{
print "Getting character sheet for $CHARNAME...\n";
system "wget -O $charfile 'http://eu.wowarmory.com/character-sheet.xml?r=Eonar&n=$CHARNAME'";
}

open CHAR, "<$charfile" or die "no $charfile";
open OUTPUT, ">$CHARNAME.html" or die "can't write to $CHARNAME.html";

print OUTPUT <<EOF
<html>
<head>
<link rel=stylesheet href="http://i.thottbot.com/css/9.css" type="text/css">
</head>
<body>
<!-- script src="http://i.thottbot.com/power.js"  -->

EOF
;

# pull the tooltip HTML from thottbot and unwrap it
sub get_cached_thott($) {
	my $itemno = $_[0];
	my $cachefile = "./itemcache/tt$itemno";
	if(-f $cachefile) {
		return `cat $cachefile`;
	}

	my $unwrap = `wget -q -O- http://thottbot.com/i$itemno/T`;
	$unwrap =~ s/T.ttload[^"]*"//;
	$unwrap =~ s/"\);$//;

die "Could not load item data for $itemno from thottbot!" unless length $unwrap;

	open CACHEFILE, ">$cachefile";
	print CACHEFILE $unwrap;
	close CACHEFILE;

	return $unwrap;
}

while(<CHAR>) {
# old armoury
#	if(/itemsArray\[\d+\]\s+=\s+\[(\d+)/) {

#        if(/staticTip itemToolTip.*id="(\d+)"/) {

	if(/item-info.xml\?i=(\d+)/) {

	my $unwrap = get_cached_thott($1);
	print OUTPUT $unwrap, "\n";

	}
}

close CHAR;
close OUTPUT;
