#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Formats as a .js file using a map: <english text> -> <localized text>.
"""

import re

from grit import util


"""The required preamble for JS files."""
_HEADER = '// This file is automatically generated by GRIT.  Do not edit.\n'


def Format(root, lang='en', output_dir='.'):
  from grit.node import empty, message
  yield _HEADER
  for item in root.ActiveDescendants():
    with item:
      if isinstance(item, message.MessageNode):
        yield _FormatMessage(item, lang)
      elif isinstance(item, empty.MessagesNode):
        yield '\n'


def _FormatMessage(item, lang):
  """Format a single message."""

  en_message = item.ws_at_start + item.Translate('en') + item.ws_at_end
  # Remove position numbers from placeholders.
  en_message = re.sub(r'%\d\$([a-z])', r'%\1', en_message)
  # Escape double quotes.
  en_message = re.sub(r'\\', r'\\\\', en_message)
  en_message = re.sub(r'"', r'\"', en_message)

  loc_message = item.ws_at_start + item.Translate(lang) + item.ws_at_end
  # Escape double quotes.
  loc_message = re.sub(r'\\', r'\\\\', loc_message)
  loc_message = re.sub(r'"', r'\"', loc_message)

  return '\nlocalizedStrings["%s"] = "%s";' % (en_message, loc_message)
