package PO4Moz::HelpFile;

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 =~ /<(p|h\d|dt|dd|th|td|div|li|title)(?:\s+[^>]*?)?>(?!(?:\s|\n)*?<(?:p|h\d|dt|dd|th|td|div|li|title)(?:\s+[^>]*?)?>)(.*?)<\/\1>/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 "")) {
    return $entries{$key}->{"translation"};
  }
  else {
    return $text;
  }
}

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

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

  $out =~ s/(<(p|h\d|dt|dd|th|td|div|li|title)(?:\s+[^>]*?)?>)(?!(?:\s|\n)*?<(?:p|h\d|dt|dd|th|td|div|li|title)(?:\s+[^>]*?)?>)(.*?)(<\/\2>)/"$1".perform_substitution($file,$2,++$entryno{$2},$3,%entries)."$4"/esgi;

  return $out;
}

1;
