package PO4Moz::HelpRDF;

use strict;
use PO4Moz::Util;
use Digest::MD5 qw(md5_hex);

sub parse {
  my $filename = shift;
  my $contents = shift;

  my %entries = ("index" => []);
  my $curentry = {};
  my %entryno = ();

  while ($contents =~ /nc:(name|title|emptysearchtext)="([^"]*)\"/sgi) {
    my $tag = lc($1);
    my $text = $2;

    if (defined $entryno{$tag}) {
      $entryno{$tag}++;
    }
    else {
      $entryno{$tag} = 1;
    }

    $curentry = {};
    $curentry->{"file"} = $filename;
    $curentry->{"comments"} = "";
    $curentry->{"key"} = "${tag}_$entryno{$tag}";
    $curentry->{"text"} = $text;

    my $key = $curentry->{"file"}.":".$curentry->{"key"};
    $entries{$key} = $curentry;
    push @{$entries{"index"}}, $key;
  }

  return %entries;
}

sub perform_substitution {
  my $file = shift;
  my $tag = lc(shift);
  my $num = shift;
  my $text = shift;
  my %entries = @_;

  my $key = "$file:${tag}_$num";
  if (defined($entries{$key})
      && ($entries{$key}->{"text"} eq $text)
      && (defined($entries{$key}->{"translation"}))
      && ($entries{$key}->{"translation"} ne "")) {
    my $ret = $entries{$key}->{"translation"};
    $ret =~ s/\"/&quot;/g;
    return $ret;
  }
  else {
    return $text;
  }
}

sub translate {
  my $file = shift;
  my $contents = shift;
  my %entries = @_;

  my %entryno = ();
  my $out = $contents;

  $out =~ s/nc:(name|title|emptysearchtext)="([^"]*)\"/"nc:$1=\"".perform_substitution($file,$1,++$entryno{$1},$2,%entries)."\""/esgi;

  return $out;
}

1;
