#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Add new Translation
    ~~~~~~~~~~~~~~~~~~~

    This script adds a new translation to the main application or a plugin.

    :copyright: (c) 2010 by the Zine Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from os import path, makedirs
from optparse import OptionParser
from datetime import datetime
from babel import Locale, UnknownLocaleError
from babel.messages import Catalog
from babel.messages.pofile import read_po, write_po
from babel.util import LOCALTZ

app_dir = 'zine'
i18n_dir = 'i18n'
app_path = path.realpath(path.join(path.dirname(__file__), path.pardir, app_dir))
app_i18n_path = path.join(app_path, i18n_dir)


def main():
    global parser
    parser = OptionParser(usage='%prog [options] language')
    parser.add_option('--plugin', dest='plugin', help='Create the '
                      'translation for this plugin.  This '
                      'has to be the full path to the plugin package.')
    options, args = parser.parse_args()
    if len(args) != 1:
        parser.error('incorrect number of arguments')

    try:
        locale = Locale.parse(args[0])
    except UnknownLocaleError, e:
        parser.error(str(e))

    if options.plugin is None:
        create_application_lang(locale)
    else:
        create_plugin_lang(locale, options.plugin)


def create_from_pot(locale, path):
    try:
        f = file(path)
    except IOError, e:
        parser.error(str(e))
    try:
        catalog = read_po(f, locale=locale)
    finally:
        f.close()
    catalog.locale = locale
    catalog.revision_date = datetime.now(LOCALTZ)
    return catalog


def write_catalog(catalog, folder):
    target = path.join(folder, str(catalog.locale))
    if not path.isdir(target):
        makedirs(target)
    f = file(path.join(target, 'messages.po'), 'w')
    try:
        write_po(f, catalog, width=79)
    finally:
        f.close()


def create_application_lang(locale):
    catalog = create_from_pot(locale, path.join(app_i18n_path, 'messages.pot'))
    write_catalog(catalog, app_i18n_path)
    print 'Created catalog for %s' % locale


def create_plugin_lang(locale, path):
    catalog = create_from_pot(locale, path.join(path, i18n_dir, 'messages.pot'))

    # incorporate existing translations from the application
    app_messages = path.join(app_i18n_path, str(locale), 'messages.po')
    if path.isfile(app_messages):
        f = file(app_messages)
        try:
            translated = read_po(f)
        finally:
            f.close()

        for message in translated:
            if message.id and message.id in catalog:
                catalog[message.id].string = message.string

    write_catalog(catalog, path.join(path, i18n_dir))
    print 'Created catalog for %s' % locale


if __name__ == '__main__':
    main()
