#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# License: MIT (see LICENSE file provided)
# vim600: fdm=marker tabstop=4 shiftwidth=4 expandtab ai
#
# This file has been modified by Manuel Saelices <msaelices _at_ yaco.es> 
# and belongs to David JEAN LOUIS <izimobil@gmail.com>.
#
# You can find more information about polib at http://code.google.com/p/polib/
#
# Description {{{
"""
**polib** allows you to manipulate, create, modify gettext files (pot, po
and mo files).  You can load existing files, iterate through it's entries,
add, modify entries, comments or metadata, etc... or create new po files
from scratch.
**polib** provides a simple and pythonic API, exporting only three
convenience functions (*pofile*, *mofile* and *detect_encoding*), and the
four core classes, *POFile*, *MOFile*, *POEntry* and *MOEntry* for creating
new files/entries.
**Basic example**:
>>> import polib
>>> # load an existing po file
>>> po = polib.pofile('tests/test_utf8.po')
>>> for entry in po:
...     # do something with entry...
...     pass
>>> # add an entry
>>> entry = polib.POEntry(msgid='Welcome', msgstr='Bienvenue')
>>> entry.occurrences = [('welcome.py', '12'), ('anotherfile.py', '34')]
>>> po.append(entry)
>>> # to save our modified po file:
>>> # po.save()
>>> # or you may want to compile the po file
>>> # po.save_as_mofile('tests/test_utf8.mo')
"""
# }}}
__author__    = 'David JEAN LOUIS <izimobil@gmail.com>'
__version__   = '0.3.1'
# dependencies {{{
try:
    import struct
    import textwrap
    import warnings
except ImportError, exc:
    raise ImportError('polib requires python 2.3 or later with the standard' \
        ' modules "struct", "textwrap" and "warnings" (details: %s)' % exc)
# }}}
__all__ = ['pofile', 'POFile', 'POEntry', 'mofile', 'MOFile', 'MOEntry',
           'detect_encoding', 'quote', 'unquote']
# shortcuts for performance improvement {{{
# yes, yes, this is quite ugly but *very* efficient
_dictget    = dict.get
_listappend = list.append
_listpop    = list.pop
_strjoin    = str.join
_strsplit   = str.split
_strstrip   = str.strip
_strreplace = str.replace
_textwrap   = textwrap.wrap
# }}}
default_encoding = 'utf-8'
def pofile(fpath, **kwargs):
    """
    Convenience function that parse the po/pot file *fpath* and return
    a POFile instance.
    **Keyword arguments**:
      - *fpath*: string, full or relative path to the po/pot file to parse
      - *wrapwidth*: integer, the wrap width, only useful when -w option was
        passed to xgettext (optional, default to 78)
      - *autodetect_encoding*: boolean, if set to False the function will
        not try to detect the po file encoding (optional, default to True)
      - *encoding*: string, an encoding, only relevant if autodetect_encoding
        is set to False
    **Example**:
    >>> import polib
    >>> po = polib.pofile('tests/test_utf8.po')
    >>> po #doctest: +ELLIPSIS
    <POFile instance at ...>
    >>> import os, tempfile
    >>> for fname in ['test_iso-8859-15.po', 'test_utf8.po']:
    ...     orig_po = polib.pofile('tests/'+fname)
    ...     tmpf = tempfile.NamedTemporaryFile().name
    ...     orig_po.save(tmpf)
    ...     try:
    ...         new_po = polib.pofile(tmpf)
    ...         for old, new in zip(orig_po, new_po):
    ...             if old.msgid != new.msgid:
    ...                 old.msgid
    ...                 new.msgid
    ...             if old.msgstr != new.msgstr:
    ...                 old.msgid
    ...                 new.msgid
    ...     finally:
    ...         os.unlink(tmpf)
    """
    # pofile {{{
    if _dictget(kwargs, 'autodetect_encoding', True) == True:
        enc = detect_encoding(fpath)
    else:
        enc = _dictget(kwargs, 'encoding', default_encoding)
    parser = _POFileParser(fpath)
    instance = parser.parse()
    instance.wrapwidth = _dictget(kwargs, 'wrapwidth', 78)
    instance.encoding  = enc
    return instance
    # }}}
def mofile(fpath, **kwargs):
    """
    Convenience function that parse the mo file *fpath* and return
    a MOFile instance.
    **Keyword arguments**:
      - *fpath*: string, full or relative path to the mo file to parse
      - *wrapwidth*: integer, the wrap width, only useful when -w option was
        passed to xgettext to generate the po file that was used to format
        the mo file (optional, default to 78)
      - *autodetect_encoding*: boolean, if set to False the function will
        not try to detect the po file encoding (optional, default to True)
      - *encoding*: string, an encoding, only relevant if autodetect_encoding
        is set to False
    **Example**:
    >>> import polib
    >>> mo = polib.mofile('tests/test_utf8.mo')
    >>> mo #doctest: +ELLIPSIS
    <MOFile instance at ...>
    >>> import os, tempfile
    >>> for fname in ['test_iso-8859-15.mo', 'test_utf8.mo']:
    ...     orig_mo = polib.mofile('tests/'+fname)
    ...     tmpf = tempfile.NamedTemporaryFile().name
    ...     orig_mo.save(tmpf)
    ...     try:
    ...         new_mo = polib.mofile(tmpf)
    ...         for old, new in zip(orig_mo, new_mo):
    ...             if old.msgid != new.msgid:
    ...                 old.msgstr
    ...                 new.msgstr
    ...     finally:
    ...         os.unlink(tmpf)
    """
    # mofile {{{
    if _dictget(kwargs, 'autodetect_encoding', True) == True:
        enc = detect_encoding(fpath)
    else:
        enc = _dictget(kwargs, 'encoding', default_encoding)
    parser = _MOFileParser(fpath)
    instance = parser.parse()
    instance.wrapwidth = _dictget(kwargs, 'wrapwidth', 78)
    instance.encoding = enc
    return instance
    # }}}
def detect_encoding(fpath):
    """
    Try to detect the encoding used by the file *fpath*. The function will
    return polib default *encoding* if it's unable to detect it.
    **Keyword argument**:
      - *fpath*: string, full or relative path to the mo file to parse.
    **Examples**:
    >>> print detect_encoding('tests/test_noencoding.po')
    utf-8
    >>> print detect_encoding('tests/test_utf8.po')
    UTF-8
    >>> print detect_encoding('tests/test_utf8.mo')
    UTF-8
    >>> print detect_encoding('tests/test_iso-8859-15.po')
    ISO_8859-15
    >>> print detect_encoding('tests/test_iso-8859-15.mo')
    ISO_8859-15
    """
    # detect_encoding {{{
    import re
    rx = re.compile(r'"?Content-Type:.+? charset=([\w_\-:\.]+)')
    f = open(fpath)
    for l in f:
        match = rx.search(l)
        if match:
            f.close()
            return _strstrip(match.group(1))
    f.close()
    return default_encoding
    # }}}
def quote(st):
    """
    Quote and return the given string *st*.
    **Examples**:
    >>> quote('\\t and \\n and \\r and " and \\\\')
    '\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\'
    """
    # quote {{{
    st = _strreplace(st, '\\', r'\\')
    st = _strreplace(st, '\t', r'\t')
    st = _strreplace(st, '\r', r'\r')
    st = _strreplace(st, '\n', r'\n')
    st = _strreplace(st, '\"', r'\"')
    return st
    # }}}
def unquote(st):
    """
    Unquote and return the given string *st*.
    **Examples**:
    >>> unquote('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\')
    '\\t and \\n and \\r and " and \\\\'
    """
    # unquote {{{
    st = _strreplace(st, r'\"', '"')
    st = _strreplace(st, r'\n', '\n')
    st = _strreplace(st, r'\r', '\r')
    st = _strreplace(st, r'\t', '\t')
    st = _strreplace(st, r'\\', '\\')
    return st
    # }}}
class _BaseFile(list):
    """
    Common parent class for POFile and MOFile classes.
    This class must **not** be instanciated directly.
    """
    # class _BaseFile {{{
    def __init__(self, fpath=None, wrapwidth=78, encoding=default_encoding):
        """
        Constructor.
        **Keyword arguments**:
          - *fpath*: string, path to po or mo file
          - *wrapwidth*: integer, the wrap width, only useful when -w option
            was passed to xgettext to generate the po file that was used to
            format the mo file, default to 78 (optional).
        """
        list.__init__(self)
        # the opened file handle
        self.fpath = fpath
        # the width at which lines should be wrapped
        self.wrapwidth = wrapwidth
        # the file encoding
        self.encoding = encoding
        # header
        self.header = ''
        # both po and mo files have metadata
        self.metadata = {}
        self.metadata_is_fuzzy = 0
    def __str__(self):
        """String representation of the file."""
        ret = []
        entries = [self.metadata_as_entry()] + \
                  [e for e in self if not e.obsolete]
        for entry in entries:
            _listappend(ret, entry.__str__(self.wrapwidth))
        for entry in self.obsolete_entries():
            _listappend(ret, entry.__str__(self.wrapwidth))
        return _strjoin('\n', ret)
    def __repr__(self):
        """Return the official string representation of the object."""
        return '<%s instance at %x>' % (self.__class__.__name__, id(self))
    def metadata_as_entry(self):
        """Return the metadata as an entry"""
        e = POEntry(msgid='')
        mdata = self.ordered_metadata()
        if mdata:
            strs = []
            for name, value in mdata:
                # Strip whitespace off each line in a multi-line entry
                value = _strjoin('\n', [_strstrip(v)
                                        for v in _strsplit(value, '\n')])
                _listappend(strs, '%s: %s' % (name, value))
            e.msgstr = _strjoin('\n', strs) + '\n'
        return e
    def save(self, fpath=None, repr_method='__str__'):
        """
        Save the po file to file *fpath* if no file handle exists for
        the object. If there's already an open file and no fpath is
        provided, then the existing file is rewritten with the modified
        data.
        **Keyword arguments**:
          - *fpath*: string, full or relative path to the file.
          - *repr_method*: string, the method to use for output.
        """
        if self.fpath is None and fpath is None:
            raise IOError('You must provide a file path to save() method')
        contents = getattr(self, repr_method)()
        if fpath is None:
            fpath = self.fpath
        mode = 'w'
        if repr_method == 'to_binary':
            mode += 'b'
        fhandle = open(fpath, mode)
        fhandle.write(contents)
        fhandle.close()
    def find(self, st, by='msgid'):
        """
        Find entry which msgid (or property identified by the *by*
        attribute) matches the string *st*.
        **Keyword arguments**:
          - *st*: string, the string to search for
          - *by*: string, the comparison attribute
        **Examples**:
        >>> po = pofile('tests/test_utf8.po')
        >>> entry = po.find('Thursday')
        >>> entry.msgstr
        'Jueves'
        >>> entry = po.find('Some unexistant msgid')
        >>> entry is None
        True
        >>> entry = po.find('Jueves', 'msgstr')
        >>> entry.msgid
        'Thursday'
        """
        try:
            return [e for e in self if getattr(e, by) == st][0]
        except IndexError:
            return None
    def ordered_metadata(self):
        """
        Convenience method that return the metadata ordered. The return
        value is list of tuples (metadata name, metadata_value).
        """
        # copy the dict first
        metadata = self.metadata.copy()
        data_order = [
            'Project-Id-Version',
            'Report-Msgid-Bugs-To',
            'POT-Creation-Date',
            'PO-Revision-Date',
            'Last-Translator',
            'Language-Team',
            'MIME-Version',
            'Content-Type',
            'Content-Transfer-Encoding'
        ]
        ordered_data = []
        for data in data_order:
            try:
                value = metadata.pop(data)
                _listappend(ordered_data, (data, value))
            except KeyError:
                pass
        # the rest of the metadata won't be ordered there are no specs for this
        keys = metadata.keys()
        keys.sort()
        for data in keys:
            value = metadata[data]
            _listappend(ordered_data, (data, value))
        return ordered_data
    def to_binary(self):
        """Return the mofile binary representation."""
        import struct
        import array
        output = ''
        offsets = []
        ids = strs = ''
        entries = self.translated_entries()
        # the keys are sorted in the .mo file
        def cmp(_self, other):
            if _self.msgid > other.msgid:
                return 1
            elif _self.msgid < other.msgid:
                return -1
            else:
                return 0
        entries.sort(cmp)
        # add metadata entry
        mentry = self.metadata_as_entry()
        mentry.msgstr = _strreplace(mentry.msgstr, '\\n', '').lstrip() + '\n'
        entries = [mentry] + entries
        entries_len = len(entries)
        for e in entries:
            # For each string, we need size and file offset.  Each string is
            # NUL terminated; the NUL does not count into the size.
            msgid = e._decode(e.msgid)
            msgstr = e._decode(e.msgstr)
            offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
            ids  += msgid  + '\0'
            strs += msgstr + '\0'
        # The header is 7 32-bit unsigned integers.
        keystart = 7*4+16*entries_len
        # and the values start after the keys
        valuestart = keystart + len(ids)
        koffsets = []
        voffsets = []
        # The string table first has the list of keys, then the list of values.
        # Each entry has first the size of the string, then the file offset.
        for o1, l1, o2, l2 in offsets:
            koffsets += [l1, o1+keystart]
            voffsets += [l2, o2+valuestart]
        offsets = koffsets + voffsets
        output = struct.pack("Iiiiiii",
                             0x950412de,        # Magic number
                             0,                 # Version
                             entries_len,       # # of entries
                             7*4,               # start of key index
                             7*4+entries_len*8, # start of value index
                             0, 0)              # size and offset of hash table
        output += array.array("i", offsets).tostring()
        output += ids
        output += strs
        return output
    # }}}
class POFile(_BaseFile):
    '''
    Po (or Pot) file reader/writer.
    POFile objects inherit the list objects methods.
    **Example**:
    >>> po = POFile()
    >>> entry1 = POEntry(
    ...     msgid="Some english text",
    ...     msgstr="Un texte en anglais"
    ... )
    >>> entry1.occurrences = [('testfile', 12),('another_file', 1)]
    >>> entry1.comment = "Some useful comment"
    >>> entry2 = POEntry(
    ...     msgid="I need my dirty cheese",
    ...     msgstr="Je veux mon sale fromage"
    ... )
    >>> entry2.occurrences = [('testfile', 15),('another_file', 5)]
    >>> entry2.comment = "Another useful comment"
    >>> entry3 = POEntry(
    ...     msgid='Some entry with quotes " \\"',
    ...     msgstr=u'Un message unicode avec des quotes " \\"'
    ... )
    >>> entry3.comment = "Test string quoting"
    >>> po.append(entry1)
    >>> po.append(entry2)
    >>> po.append(entry3)
    >>> po.header = "Some Header"
    >>> print po
    # Some Header
    msgid ""
    msgstr ""
    <BLANKLINE>
    #. Some useful comment
    #: testfile:12 another_file:1
    msgid "Some english text"
    msgstr "Un texte en anglais"
    <BLANKLINE>
    #. Another useful comment
    #: testfile:15 another_file:5
    msgid "I need my dirty cheese"
    msgstr "Je veux mon sale fromage"
    <BLANKLINE>
    #. Test string quoting
    msgid "Some entry with quotes \\" \\""
    msgstr "Un message unicode avec des quotes \\" \\""
    <BLANKLINE>
    '''
    # class POFile {{{
    def __str__(self):
        """Return the string representation of the po file"""
        ret, headers = '', _strsplit(self.header, '\n')
        for header in headers:
            if header[:1] in [',', ':']:
                ret += '#%s\n' % header
            else:
                ret += '# %s\n' % header
        return ret + _BaseFile.__str__(self)
    def save_as_mofile(self, fpath):
        """
        Save the binary representation of the file to *fpath*.
        **Keyword arguments**:
          - *fpath*: string, full or relative path to the file.
        """
        _BaseFile.save(self, fpath, 'to_binary')
    def percent_translated(self):
        """
        Convenience method that return the percentage of translated
        messages.
        **Example**:
        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> po.percent_translated()
        50
        >>> po = POFile()
        >>> po.percent_translated()
        100
        """
        total = len([e for e in self if not e.obsolete])
        if total == 0:
            return 100
        translated = len(self.translated_entries())
        return int((100.00 / float(total)) * translated)
    def translated_entries(self):
        """
        Convenience method that return a list of translated entries.
        **Example**:
        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> len(po.translated_entries())
        6
        """
        return [e for e in self if e.translated() and not e.obsolete]
    def untranslated_entries(self):
        """
        Convenience method that return a list of untranslated entries.
        **Example**:
        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> len(po.untranslated_entries())
        6
        """
        return [e for e in self if not e.translated() and not e.obsolete]
    def fuzzy_entries(self):
        """
        Convenience method that return the list of 'fuzzy' entries.
        **Example**:
        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> len(po.fuzzy_entries())
        2
        """
        return [e for e in self if 'fuzzy' in e.flags]
    def obsolete_entries(self):
        """
        Convenience method that return the list of obsolete entries.
        **Example**:
        >>> import polib
        >>> po = polib.pofile('tests/test_pofile_helpers.po')
        >>> len(po.obsolete_entries())
        4
        """
        return [e for e in self if e.obsolete]
    def merge(self, refpot):
        """
        XXX this could not work if encodings are different, needs thinking
        and general refactoring of how polib handles encoding...
        Convenience method that merge the current pofile with the pot file
        provided. It behaves exactly as the gettext msgmerge utility:
          - comments of this file will be preserved, but extracted comments
            and occurrences will be discarded
          - any translations or comments in the file will be discarded,
            however dot comments and file positions will be preserved
        **Keyword argument**:
          - *refpot*: object POFile, the reference catalog.
        **Example**:
        >>> import polib
        >>> refpot = polib.pofile('tests/test_merge.pot')
        >>> po = polib.pofile('tests/test_merge_before.po')
        >>> po.merge(refpot)
        >>> expected_po = polib.pofile('tests/test_merge_after.po')
        >>> str(po) == str(expected_po)
        True
        """
        for entry in refpot:
            e = self.find(entry.msgid)
            if e is None:
                # entry is not in the po file, we must add it
                # entry is created with msgid, occurrences and comment
                self.append(POEntry(
                    msgid=entry.msgid,
                    occurrences=entry.occurrences,
                    comment=entry.comment
                ))
            else:
                # entry found, we update it...
                e.occurrences = entry.occurrences
                e.comment = entry.comment
        # ok, now we must "obsolete" entries that are not in the refpot
        # anymore
        for entry in self:
            if refpot.find(entry.msgid) is None:
                entry.obsolete = True
    # }}}
class MOFile(_BaseFile):
    '''
    Mo file reader/writer.
    MOFile objects inherit the list objects methods.
    **Example**:
    >>> mo = MOFile()
    >>> entry1 = POEntry(
    ...     msgid="Some english text",
    ...     msgstr="Un texte en anglais"
    ... )
    >>> entry2 = POEntry(
    ...     msgid="I need my dirty cheese",
    ...     msgstr="Je veux mon sale fromage"
    ... )
    >>> entry3 = MOEntry(
    ...     msgid='Some entry with quotes " \\"',
    ...     msgstr=u'Un message unicode avec des quotes " \\"'
    ... )
    >>> mo.append(entry1)
    >>> mo.append(entry2)
    >>> mo.append(entry3)
    >>> print mo
    msgid ""
    msgstr ""
    <BLANKLINE>
    msgid "Some english text"
    msgstr "Un texte en anglais"
    <BLANKLINE>
    msgid "I need my dirty cheese"
    msgstr "Je veux mon sale fromage"
    <BLANKLINE>
    msgid "Some entry with quotes \\" \\""
    msgstr "Un message unicode avec des quotes \\" \\""
    <BLANKLINE>
    '''
    # class MOFile {{{
    def __init__(self, fpath=None, wrapwidth=78):
        """
        MOFile constructor.
        See _BaseFile.__construct.
        """
        _BaseFile.__init__(self, fpath, wrapwidth)
        self.magic_number = None
        self.version = 0
    def save_as_pofile(self, fpath):
        """
        Save the string representation of the file to *fpath*.
        **Keyword argument**:
          - *fpath*: string, full or relative path to the file.
        """
        _BaseFile.save(self, fpath)
    def save(self, fpath):
        """
        Save the binary representation of the file to *fpath*.
        **Keyword argument**:


Answer:           - *fpath*: string, full or relative path to the file.