import click
import os
import glob
from common.translate import (
    availables_locales, locales_dir, convert_pot2po,
    form_i18n_file_import, menu_i18n_file_import,
    delete_i18n_lang, clean_pot2po)


@click.command("pot2po")
def pot_to_po():
    """Update PO files with POT template"""

    pot_files = [
        'form.pot',
    ]

    for pot in pot_files:
        potfile = os.path.join(locales_dir, pot)
        for al in availables_locales:
            pofile = os.path.join(locales_dir, al, 'LC_MESSAGES', pot.replace('.pot', '.po'))
            print("Update %s %s po file" % (pot, al))
            convert_pot2po(pofile, potfile)
            clean_pot2po(pofile)

    potfile = os.path.join(locales_dir, 'menu.pot')
    for al in availables_locales:
        pofile = os.path.join(locales_dir, al, 'LC_MESSAGES', 'menu.po')
        print("Update menu %s po file" % al)
        convert_pot2po(pofile, potfile)

    print('Merge PO with catalogs done')


@click.command("i18n")
def i18n_app():
    """read and insert catalog for each language"""

    print("Synchronise lang in the database")
    print("Locales folder: " + locales_dir)
    for fold in glob.glob(locales_dir + '/**/LC_MESSAGES'):
        print("Update " + fold.split(os.sep)[-2] + " translation")
        delete_i18n_lang(fold.split(os.sep)[-2])
        form_i18n_file_import(os.path.join(fold, 'form.po'), fold.split(os.sep)[-2])
        menu_i18n_file_import(os.path.join(fold, 'menu.po'), fold.split(os.sep)[-2])
    print("Sync lang done.")
