## Active Perl 5.8.8 or later

# Add comments to WalkerRoutes.xml
# 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 $npcstring_txt = './lang/ja/npcstring.txt';

my $DEBUG = 0; # 1 or 0

my $LogFile = UTF8(__FILE__);
   $LogFile =~ s!\.[^.\/\\]*$!.log!;
open LOG, '>:utf8', FS($LogFile)  or die "'$LogFile' $!";

my %npcstring = ();
&loadNpcStringAll();

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');

&start('./WalkerRoutes.xml');

close LOG;
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 $line (@T) {
		if ($line =~ m/npcStringId="(\d+)"/) {	#L2J_DataPack_BETA r8271
			my $id = $1;
			my $string = $npcstring{$id};
		#	$string =~ s/</&lt;/g;
		#	$string =~ s/>/&gt;/g;
		#	$string =~ s/--/__/g;
			$line =~ s/[\t ]*<!--.*-->$//;
			$line =~ s/$/ <!-- "$string" -->/;
		}
		elsif ($line =~ m/string="#(\d+)"/) {	#L2J_DataPack
			my $id = $1;
			my $string = $npcstring{$id};
		#	$string =~ s/</&lt;/g;
		#	$string =~ s/>/&gt;/g;
		#	$string =~ s/--/__/g;
			$line =~ s/[\t ]*<!--.*-->$//;
			$line =~ s/$/ <!-- "$string" -->/;
		}
		elsif ($line =~ m/npcId="(\d+)"/) {
			my $id = $1;
			my $name = getNpcName($id);
			if ($name) {
				$line =~ s/[\t ]*<!--.*-->$//;
				$line =~ s/$/ <!-- $name -->/;
			}
		}
	}
	$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 loadNpcStringAll {
	open FILE,'<:utf8',FS($npcstring_txt)  or do {warn "'$npcstring_txt' $!";exit 0};
	while (not eof FILE) {
		my $line = <FILE>;
		next if $line =~ m!^/!;
		chomp $line;
		my ($N_id, $N_name) = split /\t/, $line;
		$npcstring{$N_id} = $N_name
	}
	close FILE;
}

sub getNpcName {
	my ($id) = @_;

	my $sql = "SELECT name,title FROM npc WHERE id=?";
	my $sth = $db->prepare($sql);
	$sth->execute($id) or die DBI::errstr;
	$sth->bind_columns(undef, \(my($N_name,$N_title))) or die DBI::errstr;
	my $rc = $sth->fetch();

	my $ret = $N_title ? "$N_title $N_name" : $N_name;
	return $ret;
}
