#! /usr/bin/perl

# Determine the keys that should be in the locale file,
# and the number of arguments the keys should have

use strict;
use File::Find;

if (scalar @ARGV != 2) {
	die("Usage: $0 <SRCDIR> <OUTFILE>")
}

my $indir = $ARGV[0];
my $outfile = $ARGV[1];

our %found;

find(\&doit, $indir);

sub arg_count {
	return scalar split(/,/,$_[0]);
}

sub make_comment {
	my $input = $_[0];
	$input =~ s/(_[A-Z])/_COMMENT$1/g;
	return $input;
}

# for each .cpp/.hpp file, collect locale calls
sub doit {
	my $file = $File::Find::name;
	if (!($file =~ /\..pp$/)) {
		return;
	}
	
	# relative filename
	#print "$file\n";
	$file =~ s@.*/@@;
	
	# Read file
	open F, "< $file";
	my $body = join('',<F>);
	close F;
	
	# Custom argument expansion
	my $inparen;
	$inparen = qr/[^()]|\((??{$inparen})*\)/; # recursive paren matching
	$body =~ s/format_string\((_[A-Z]+)(_\([^)]+\)),($inparen+)/
	           $1 . "_" . arg_count($3) . $2
	          /ge;
	$body =~ s/action_name_for[(][^,]*,\s*(_[A-Z]+)(_\([^)]+\))/$1_1$2/g;
	
	# Drop comments, mark found items as 'optional'
	$body =~ s@//[^\n]*@ find_locale_calls($&, 1)@ge;
	$body =~ s@/\*.*?\*/@find_locale_calls($&, 1)@ge;
	
	find_locale_calls($body, 0);
}

sub find_locale_calls {
	my $body       = $_[0];
	my $in_comment = $_[1];
	
	# Find calls to locale functions
	while ($body =~ /_(COMMENT_)?(MENU|HELP|TOOL|TOOLTIP|LABEL|BUTTON|TITLE|TYPE|ACTION|ERROR)_(?:([1-9])_)?\(\s*\"([^\"]+)\"/g) {
		my $argc = $3 ? $3 : 0;
		if (defined($found{$2}{$4}{'argc'}) && $found{$2}{$4}{'argc'} != $argc) {
			print "ERROR: key _$2_($4) used with different arities";
		}
		$found{$2}{$4}{'opt'}  = defined($found{$2}{$4}{'opt'}) ? ($found{$2}{$4}{'opt'} && $in_comment) : $in_comment;
		$found{$2}{$4}{'argc'} = $argc;
	}
	# Also translated:
	while ($body =~ m@
	                 ( addPanel        \((?:[^,]+,){6} # gui/set/window.cpp
	                 )
	                 \s* _ \(\" ([^\"]+) \"\)
	                @xg
	      ) {
		my $key;
		($key = $2) =~ s/_/ /g;
		foreach my $type ("MENU","HELP","TOOL","TOOLTIP") {
			$found{$type}{$key}{'opt'}  = $in_comment;
			$found{$type}{$key}{'argc'} = 0;
		}
	}
}

# Now process the items we found, write thea list in MSE reader format

open my $fh, "> $outfile";
print $fh "# This file contains the keys expected to be in MSE locales\n";
print $fh "# It was automatically generated by tools/locale/locale.pl\n";
print $fh "# Generated on " . localtime . "\n\n";

my @types = sort keys %found;
foreach my $type (@types) {
	print $fh lc($type) . ":\n";
	my @keys = sort keys %{$found{$type}};
	foreach my $key (@keys) {
		my $argc = $found{$type}{$key}{'argc'};
		my $opt  = $found{$type}{$key}{'opt'} ? 'optional, ' : '';
		print $fh "\t$key: $opt$argc\n";
	}
}