package PO4Moz::MozDTD;

use strict;
use PO4Moz::Util;

sub parse {
  my $filename = shift;
  my $contents = shift;
  
  # Remove trailing whitespace
  $contents =~ s/(\s|\n)*$//s;

  my %entries = ("index" => []);
  my $curentry = {};
  while ($contents ne "") {
    # Remove leading whitespace
    $contents =~ s/^(\s|\n)*//s;

    $curentry->{"file"} = $filename;
    $curentry->{"comments"} = "";
    
    # Remove SYSTEM entities and calls to them
    # (or at least I think that's their name)
    $contents =~ s/^<!ENTITY(\s|\n)+%(\s|\n)+\S+(\s|\n).*?>(\s|\n)*//s;
    $contents =~ s/^%\S+;(\s|\n)*//s;
    
    # Find comments
    while ($contents =~ s/^<!--(.*?)-->(?:\s|\n)*//s) {
      $curentry->{"comments"} .= "$1\n";
    }

    if ($contents ne "") {  
      # Find entity
      if ($contents =~ s/^<!ENTITY(?:\s|\n)+(\S+)(?:\s|\n)+((?:(["'])(?:\\\3|.)*?\3)(?:\s|\n)*)>//s) {
        # fix quote b0rkage in editors with an extra double-quote "
        $curentry->{"key"} = $1;
        $curentry->{"text"} = PO4Moz::Util::dtd_unquote_string($2);
      }
      else {
        $contents =~ /^(.*?)(\n|$)/s;
        print STDERR "Parse error in file $filename at $1\n";
        exit 1;
      }
    
      my $key = $curentry->{"file"}.":".$curentry->{"key"};
      $entries{$key} = $curentry;
      push @{$entries{"index"}}, $key;
      $curentry = {};
    }
  }

  return %entries;
}

sub translate {
  my $file = shift;
  my $contents = shift;
  my %entries = @_;
  my $out = "";
  my $end = "";
  
  # Discount trailing whitespace
  $contents =~ s/((\s|\n)*)$//;
  $end = $1;

  while ($contents ne "") {
    # Discount leading whitespace
    if ($contents =~ s/^((\s|\n)*)//) {
      $out .= $1;
    }

    # Discount SYSTEM entities and calls to them
    # (or at least I think that's their name)
    if ($contents =~ s/^(<!ENTITY(\s|\n)+%(\s|\n)+\S+(\s|\n).*?>(\s|\n)*)//s) {
      $out .= $1;
    }
    if ($contents =~ s/^(%\S+;(\s|\n)*)//s) {
      $out .= $1;
    }
    
    # Find comments
    while ($contents =~ s/^(<!--(.*?)-->(?:\s|\n)*)//s) {
      $out .= $1;
    }
  
    if ($contents ne "") {
      # Find entity
      if ($contents =~ s/^(<!ENTITY(?:\s|\n)+(\S+)(?:\s|\n)+)((["'])(?:\\\4|.)*?\4)((?:\s|\n)*>)//s) {
        # fix quote b0rkage in editors with an extra double-quote "
        my $key = "$file:$2";
        my $text = $entries{"$key"}->{"translation"};
        if (!$text) {
          $text = $entries{"$key"}->{"text"};
        }
        if ($text) {
          $out .= "$1".PO4Moz::Util::dtd_quote_string($text)."$5";
        } else {
          $out .= "$1$3$5";
        }
      }
      else {
        $contents =~ /^(.*?)(\n|$)/s;
        print STDERR "Parse error in file $file at $1\n";
        exit 1;
      }
    }
  }

  $out = "$out$end";
  return $out;
}  

1;
