package PO4Moz::ContentsRDF;

use strict;
use PO4Moz::Util;

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

  # This is gonna be easy.
  # We only want to be able to parse global/contents.rdf
  
  $filename = "contents.rdf";

  my %entries = ("index" => []);
  my $curentry = {"file" => $filename, "comments" => ""};

  foreach my $key ("displayName", "name") {
    if ($contents =~ /<RDF:Description\s+(?:[^>]+\s+)*chrome:$key="(.*?)"/s) {
      # sigh "
      $curentry->{"key"} = "chrome.$key";
      $curentry->{"text"} = $1;
      
      $entries{"$filename:chrome.$key"} = $curentry;
      push @{$entries{"index"}}, "$filename:chrome.$key";
      $curentry = {};
    }
  }

  return %entries;
}

sub translate {
  my $file = shift;
  my $contents = shift;
  my %entries = @_;
  my $out = "";
  
  # easy too?

  $file = "contents.rdf";
  $out = $contents;
  my $locale = "";
  my $displayName = "";
  if ($entries{"$file:chrome.name"}) {
    $locale = $entries{"$file:chrome.name"}->{"translation"};
    if (!$locale) {
      $locale = $entries{"$file:chrome.name"}->{"text"};
    }
  }
  elsif ($entries{"install.rdf:locale"}) {
    $locale = $entries{"install.rdf:locale"}->{"translation"};
    if (!$locale) {
      $locale = $entries{"install.rdf:locale"}->{"text"};
    }
  }

  if ($entries{"$file:chrome.displayName"}) {
    $displayName = $entries{"$file:chrome.displayName"}->{"translation"};
    if (!$displayName) {
      $displayName = $entries{"$file:chrome.displayName"}->{"text"};
    }
  }
  elsif ($entries{"install.rdf:prettyName"}) {
    $displayName = $entries{"install.rdf:prettyName"}->{"translation"};
    if (!$displayName) {
      $displayName = $entries{"install.rdf:prettyName"}->{"text"};
    }
  }

  if ($locale) {
    $out =~ s/urn:mozilla:locale:[^:"]+-[^:"]+/urn:mozilla:locale:$locale/sg;
    $out =~ s/chrome:name=".*?"/chrome:name="$locale"/sg;
  }

  if ($displayName) {
    $out =~ s/chrome:displayName=".*?"/chrome:displayName="$displayName"/sg;
  }
  
  # a piece of cake

  return $out;
}  

1;
