#!/usr/bin/python2.7
from __future__ import unicode_literals

import argparse
import os.path
import sys
from lxml import etree

import rad.pagelib as pagelib

parser = argparse.ArgumentParser()

parser.add_argument("-o", "--output", dest="outfile", metavar="OUTPUT_FILE", required=True)
parser.add_argument("infiles", metavar="INPUT_FILE", nargs="+")

args = parser.parse_args()

translator = pagelib.Translator(is_stub=False)

# collect message IDs from pages
for path in args.infiles:
    try:
        root = pagelib.open_page(path, translator)
        pagelib.parse_page(root, path, translator, "C")
    except (etree.LxmlError, pagelib.PageParserException) as e:
        #rad.console.warn()
        print("Could not parse page '{}', skipping:".format(path))
        print("{}: {}".format(type(e).__name__, e.message))

# write out .po file
# TODO: if args.outfile already exists, merge strings into args.pofile
if os.path.exists(args.outfile) and not translator.differs_from(args.outfile):
    print("No changes made to '{}'.".format(args.outfile))
else:
    translator.write_out(args.outfile)
    print("Successfully generated '{}'.".format(args.outfile))
