package PO4Moz::MozProp;

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"} = "";

    # Find comments
    while ($contents =~ s/^#(.*?)(\n|$)//s) {
      $curentry->{"comments"} .= "$1\n";
      # Remove more whitespace
      $contents =~ s/^(\s|\n)*//s;
    }

    if ($contents ne "") {
      # Find property
      if ($contents =~ s/^(\S+?)(?:\s|\n)*=((?:\\\n|.)*?)(?:\n|$)//s) {
        # fix quote b0rkage in editors with an extra double-quote "
        my ($key, $text) = ($1, $2);
        $text =~ s/^\s*//;
        $curentry->{"key"} = $key;
        $curentry->{"text"} = PO4Moz::Util::unescape_string($text);
      }
      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;
    }

    # Find comments
    while ($contents =~ s/^(#(.*?)(\n|$))//s) {
      $out .= $1;
      # Discount more whitespace
      $contents =~ s/^((\s|\n)*)//;
      $out .= $1;
    }

    if ($contents ne "") {
      # Find property
      if ($contents =~ s/^((\S+?)(?:\s|\n)*=)((?:\\\n|.)*?)(\n|$)//s) {
        my $key = "$file:$2";
        my $text = $entries{"$key"}->{"translation"};
        if (!$text) {
          $text = $entries{"$key"}->{"text"};
        }
        if ($text) {
          $out .= "$1".PO4Moz::Util::prop_quote_string($text)."$4";
        } else {
          $out .= "$1$3$4";
        }
      }
      else {
        $contents =~ /^(.*?)(\n|$)/s;
        print STDERR "Parse error in file $file at $1\n";
        exit 1;
      }
    }
  }

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

1;
