#!/usr/bin/env python
# coding: utf8
# vim: ts=4 expandtab

"""Module for checking message count"""

from xml.etree import cElementTree as etree
from lxml import etree
import argparse
import sys

IGNORE_GROUPS = ('changelog_records',)
IGNORE_NAMES = ('msg_help_links',)

def ispsystem_help():
    """ Show ispsystem help """
    sys.stdout.write("(c) ISPsystem.com")
    sys.exit(0)


def convert_xml_to_set(xmlfile, lang, plugin=False):
    """ Get all messages to set """
    doc = etree.parse(xmlfile)
    msg_set = set()
    xpath = ".//lang[@name='" + lang + "']/messages"
    for msggroup in doc.xpath(xpath):
        msg_group_name = msggroup.get('name')
        if plugin and msg_group_name != 'plugin':
            continue # Ignoring theese groups
        if msg_group_name in IGNORE_GROUPS:
            continue # Ignoring theese groups
        for msg in msggroup.findall('msg'):
            msg_name = msg.get('name')
            if msg_name in IGNORE_NAMES:
                continue # Ignoring theese names
            if msg.text is not None: # Если пустая мессага, игнорируем
                msg_set.add((msg_group_name, msg_name))
    return msg_set


def main():
    """ main func"""
    if sys.argv[1] == '-T':
        ispsystem_help()

    parser = argparse.ArgumentParser()
    parser.add_argument('ru_xml', help='Path to ru msg xml or "-T"')
    parser.add_argument('en_xml', help='Path to en msg xml file', nargs='*')
    parser.add_argument('--release', action='store_true')
    parser.add_argument('--plugin', action='store_true')

    args = parser.parse_args()

    ru_msg_set = convert_xml_to_set(args.ru_xml, 'ru', plugin=args.plugin)
    en_msg_set = set()
    for xmlfile in args.en_xml:
        en_msg_set.update(convert_xml_to_set(xmlfile, 'en', plugin=args.plugin))
    diff = ru_msg_set - en_msg_set
    if diff:
        print 'Different between RU and EN message files'
        print '=' * 10
        for elem in diff:
            print elem
        print '=' * 10
        if args.release:
            sys.exit(1)


if __name__ == '__main__':
    main()
