#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`


    compile-translation-catalogs
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Compile the existing translation catalogs.
'''

# Import python libs
import os
import sys
import fnmatch

# Import 3rd-party libs
HAS_BABEL = False
try:
    from babel.messages import mofile, pofile
    HAS_BABEL = True
except ImportError:
    try:
        import polib
    except ImportError:
        print(
            'You need to install either babel or pofile in order to compile '
            'the message catalogs. One of:\n'
            '    pip install babel\n'
            '    pip install polib'
        )
        sys.exit(1)

DOC_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
LOCALES_DIR = os.path.join(DOC_DIR, 'locale')


def main():
    '''
    Run the compile code
    '''

    print('Gathering the translation catalogs to compile...'),
    sys.stdout.flush()
    entries = {}
    for locale in os.listdir(os.path.join(LOCALES_DIR)):
        if locale == 'pot':
            continue

        locale_path = os.path.join(LOCALES_DIR, locale)
        entries[locale] = []

        for dirpath, _, filenames in os.walk(locale_path):
            for filename in fnmatch.filter(filenames, '*.po'):
                entries[locale].append(os.path.join(dirpath, filename))
    print('DONE')

    for locale, po_files in sorted(entries.items()):
        lc_messages_path = os.path.join(LOCALES_DIR, locale, 'LC_MESSAGES')
        print('\nCompiling the {0!r} locale:'.format(locale))
        for po_file in sorted(po_files):
            relpath = os.path.relpath(po_file, lc_messages_path)
            print '  {0}.po -> {0}.mo'.format(relpath.split('.po', 1)[0])
            if HAS_BABEL:
                catalog = pofile.read_po(open(po_file))
                mofile.write_mo(
                    open(po_file.replace('.po', '.mo'), 'wb'), catalog
                )
                continue

            catalog = polib.pofile(po_file)
            catalog.save_as_mofile(fpath=po_file.replace('.po', '.mo'))

    print('Done')


if __name__ == '__main__':
    main()
