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

    This script adds a new translation to Zine or a Zine plugin.

    :copyright: (c) 2009 by the Zine Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from os import makedirs
from os.path import dirname, join, realpath, pardir, isdir, isfile
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

zine = realpath(join(dirname(__file__), '..', 'zine'))

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 = join(folder, str(catalog.locale))
    if not isdir(target):
        makedirs(target)
    f = file(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, join(zine, 'i18n', 'messages.pot'))
    write_catalog(catalog, join(zine, 'i18n'))
    print 'Created catalog for %s' % locale


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

    # incorporate existing translations from the application
    zinepath = join(zine, 'i18n', str(locale), 'messages.po')
    if isfile(zinepath):
        f = file(zinepath)
        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, join(path, 'i18n'))
    print 'Created catalog for %s' % locale


if __name__ == '__main__':
    main()
