#!/usr/bin/env python
import polib
import codecs
import sys
import os
import re
import optparse

scriptPath = os.path.realpath(__file__)
rootSrcDir = os.path.dirname(os.path.dirname(scriptPath))

def save(lang, translation):
    lang = lang.replace('_', '-')
    if not os.path.isdir(rootSrcDir + '/unity-firefox-extension/locale/' + lang):
        os.mkdir(rootSrcDir + '/unity-firefox-extension/locale/' + lang)
        print('created ' + rootSrcDir + '/unity-firefox-extension/locale/' + lang)

        manifest = open(rootSrcDir + '/unity-firefox-extension/chrome.manifest', 'a')
        manifest.write('locale unity ' + lang + ' locale/' + lang + '/\n')
        manifest.close()
    lines = open(rootSrcDir + '/unity-firefox-extension/locale/en-US/unity_webapps.properties', 'r').readlines()

    out = codecs.open(rootSrcDir + '/unity-firefox-extension/locale/' + lang + '/unity_webapps.properties', "w", "utf-8")
    for line in lines:
        msg = line[line.find('=') + 1:].strip()
        id = line[:line.find('=')].strip()
        if msg in translation:
            msg = translation[msg]
        out.write(id + ' = ' + msg + '\n')
    out.close()

for root, dirs, files in os.walk(rootSrcDir + '/po'):
    for name in files:
        match = re.search('(.+)\.po$', name)
        if not match:
            continue
        lang = match.groups()[0]
        po = polib.pofile(os.path.join(root, name))
        t = {}
        for entry in po:
            if entry.obsolete or entry.msgstr == '':
                continue
            t[entry.msgid] = entry.msgstr;
        save(lang, t)
