#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import os
import subprocess
from dontpanic.i18nlib import _, i18n_domain
from dontpanic.utils import localedir, podir, progname, setup_logging

from argparse import ArgumentParser
from glob import glob


logger = logging.getLogger(__name__)


def update_pot():
    if not os.path.exists(podir):
        os.makedirs(podir)

    cmd = ['xgettext', '--language=Python', '--package-name', i18n_domain,
           '--output', '{}/{}.pot'.format(podir, i18n_domain)]
    for path, names, filenames in os.walk(os.path.join(os.curdir, "dontpanic")):
        for f in filenames:
            if f.endswith('.py'):
                cmd.append(os.path.join(path, f))
    subprocess.call(cmd)


def update_po():
    source_pot = os.path.join(podir, '{}.pot'.format(i18n_domain))
    for po_file in glob(os.path.join(podir, '*.po')):
        subprocess.check_call(["msgmerge", "--update", po_file, source_pot])


def update_mo():
    for filename in os.listdir(podir):
        if not filename.endswith('.po'):
            continue

        lang = filename[:-3]
        src = os.path.join(podir, filename)
        dest_path = os.path.join(localedir, lang, 'LC_MESSAGES')
        dest = os.path.join(dest_path, i18n_domain + '.mo')

        if not os.path.exists(dest_path):
            os.makedirs(dest_path)

        if not os.path.exists(dest):
            logger.info('Compiling {}'.format(src))
            subprocess.call(["msgfmt", src, "--output-file", dest])
        else:
            src_mtime = os.stat(src)[8]
            dest_mtime = os.stat(dest)[8]
            if src_mtime > dest_mtime:
                logger.info('Compiling {}'.format(src))
                subprocess.call(["msgfmt", src, "--output-file", dest])


if __name__ == "__main__":
    parser = ArgumentParser(prog=progname, description=_("Update translation for Dontpanic."))

    parser.add_argument("-v", "--verbose", action="count", default=0, help=_("Increase output verbosity"))

    parser.add_argument("-pot", "--update_pot", action="store_true", help=_("Update template for translators"))
    parser.add_argument("-po", "--update_po", action="store_true", help=_("Update .po files from .pot file"))
    parser.add_argument("-mo", "--update_mo", action="store_true", help=_("Compile .po files into .mo files"))

    args = parser.parse_args()
    setup_logging(args.verbose)

    if args.update_pot:
        update_pot()

    if args.update_po:
        update_po()

    if args.update_mo:
        update_mo()
