#!/usr/bin/python
import sys
import os
import polib
import json
import cStringIO
import collections

# processing arguments
# ---------------------
# pomessages.py app/root locale [project:default is empty] [filename:default=django]
# pomessages.py third/party/app/root ru projectname destinationfile

# path - root of translatable project
path = len(sys.argv) > 1 and sys.argv[1] or None
path = path and os.path.abspath(path) or None

# locale to extract from
locale = len(sys.argv) > 2 and sys.argv[2] or None

# project name
project = len(sys.argv) > 3 and sys.argv[3] or ''
project = project and '%s:' % project

# project name
filename = len(sys.argv) > 4 and sys.argv[4] or 'django'

# io - content of python file, po - po file
io = cStringIO.StringIO()
po = polib.POFile()


if not path or not locale:
    exit('Root path not specified.')

registry = collections.OrderedDict()
for root, dirs, files in os.walk(path):
    for file in files:
        if not file.endswith('.po'):
            continue

        realroot = os.path.abspath(os.path.join(root, '../../..')).replace('\\', '/')
        pofile = os.path.abspath(os.path.join(root, file)).replace('\\', '/')
        related = os.path.relpath(realroot, path).replace('\\', '/')
        curloc = os.path.relpath(pofile, realroot).replace('\\', '/').split('/')[1]

        if not curloc == locale:
            continue

        # get po file
        posource = polib.pofile(pofile)
        if not po.metadata and posource.metadata:
            po.metadata = posource.metadata

        # generate result
        # directory title
        _ = '\n\n# %s%s (source:%s) directory translations' % (project, related, curloc)
        io.write(_)
        io.write('\n# %s' % ('-' * (len(_)-3)))

        for elem in posource:
            # add entry to result python file
            io.write('\n_(%s) # %s' % (
                json.dumps(elem.msgid),
                ', '.join(['%s%s:%s' % (project, os.path.join(related, source).replace('\\', '/'), line,)
                           for source, line in elem.occurrences]),
            ))

            # add entry to po registry
            if (elem.msgid not in registry or
                elem.msgstr and not registry.get(elem.msgid).msgstr):
                registry.update(**{elem.msgid: elem,})

# write python polines file
with open(os.path.join(path, '%s.py' % filename), 'w') as handler:
    io.seek(0)
    handler.write(io.read())
    io.close()

# write po file
if len(registry):
    for elem in registry.values():
        po.append(elem)
    po.save(os.path.join(path, '%s.po' % filename))