## Active Perl 5.8.8 or later

# Author JOJO

use utf8;
use strict;
use warnings;
use Encode;
use DBI;

binmode STDOUT,':encoding(cp932)'; $|=1;
sub   FS {Encode::encode('cp932',shift)}
sub UTF8 {Encode::decode('cp932',shift)}

my $DEBUG = 0; # 1 or 0

my $vars_txt = '../../../../../tools/vars.txt';
open FILE,'<',$vars_txt  or do {warn "'$vars_txt' $!";exit 0};
read FILE,my $vars,-s FILE;
close FILE;
my $gsuser = ($vars =~ m/^@*set gsuser=(.+)$/m)[0];
my $gspass = ($vars =~ m/^@*set gspass=(.+)$/m)[0];
my $gsdb   = ($vars =~ m/^@*set gsdb=(.+)$/m)[0];
my $gshost = ($vars =~ m/^@*set gshost=(.+)$/m)[0];

my $db = DBI->connect("DBI:mysql:$gsdb:$gshost", $gsuser, $gspass, {mysql_enable_utf8=>1}) or do{warn DBI::errstr;exit 0};
   $db->do('SET NAMES UTF8');

my %itemname = ();
my %skillname = ();
&loadItemNameAll();
&loadSkillNameAll();

opendir DIR, '.'  or die $!;
my @files = grep m/\.xml$/, map {UTF8($_)} readdir DIR;
closedir DIR;

&start($_) for @files;

exit 0;

sub start {
	my ($filePath) = @_;

	print "$filePath\n" if $DEBUG;
	open FILE, '<:utf8', FS($filePath) or die "'$filePath' $!";
	my $mtime = (stat FILE)[9];
	read FILE,my $text,-s FILE;
	close FILE;

	my $backup = $text;
	my @T = split m/(?<=[\n])/, $text;
	for (my $i = 0; $i <= $#T; ++$i) {
		my $line = $T[$i];

		if ($line =~ m{<\w*skill id="(\d+)" level="(\d+)" */>}) {
			my $skillId = $1;
			my $skillLevel = $2;
			my $skillName = $skillname{$skillId * 10000 + $skillLevel};
			$T[$i] =~ s{(?<=>) +<!--.+?-->$}{};
			$T[$i] =~ s{$}{ <!-- $skillName -->};
			print "\t$skillName\n" if $DEBUG;
		}
		elsif ($line =~ m{<\w+ id="(\d+)" */>}) {
			my $itemId = $1;
			my $itemName = $itemname{$itemId};
			$T[$i] =~ s{(?<=>) +<!--.+?-->$}{};
			$T[$i] =~ s{$}{ <!-- $itemName -->};
			print "\t$itemName\n" if $DEBUG;
		}
	}
	$text = join '',@T;

	if ($backup ne $text) {
		my $outPath = $filePath;
		   $outPath = $filePath . '.text' if $DEBUG;
		open FILE, '>:utf8', FS($outPath) or die "'$outPath' $!";
		print FILE $text;
		close FILE;
		utime $mtime, $mtime, FS($outPath);
	}
}

sub loadItemNameAll {
	my $sth = $db->prepare("SELECT id,name FROM itemname_ja");
	$sth->execute or die DBI::errstr;
	$sth->bind_columns(undef, \(my($N_id,$N_name))) or die DBI::errstr;

	while (my $rc = $sth->fetch()) {
		$itemname{$N_id} = $N_name;
	}
}
sub loadSkillNameAll {
	my $sth = $db->prepare("SELECT id,level,name FROM skillname_ja");
	$sth->execute or die DBI::errstr;
	$sth->bind_columns(undef, \(my($N_id,$N_level,$N_name))) or die DBI::errstr;

	while (my $rc = $sth->fetch()) {
		$skillname{$N_id * 10000 + $N_level} = $N_name;
	}
}
