#!/usr/bin/env python
"""
wmltest -- tool to test the integrity and meaning of WML.

Use --help to see usage.
"""
#TODO:
#-Include linenumbers and filenames in "complaint messages"
#-Write function to check dependencies
#-Create a way to do linking PLUS some extra tag-specific things.
#List of dependencies to check:
#-defense,movement_costs: keys should be valid terrain
#-resistance: keys should be valid damage types
#-effect: valid keys vary depending on name

import wesnoth.wmldata as wmldata
import wesnoth.wmlparser as wmlparser
# Not needed yet
#import wesnoth.wmltools as wmltools
import wesnoth.wmlgrammar as wmlgrammar
import re

class Tester:
    """
    The Tester class, this walks the WML tree and checks whether stuff has meaning. (among other things)
    """
    def __init__(self, wmltree, verbosity):
        self.wmltree = wmltree
        self.verbosity = verbosity
        self.grammar = wmlgrammar.Grammar().grammar()
    def test(self, tag=None, depth=0):
        """Tests whether things have meaning, walks the wml tree."""
        if not tag:
            tag = self.wmltree
        if self.verbosity > 2:
            print "%s[%s]" % (depth * ' ', tag.name, )
        for item in tag.data:
            if isinstance(item, wmldata.DataSub):
                if item.name in self.grammar[tag.name][0]:
                    self.test(item, depth + 1)
                else:
                    # FIXME: this code is *UGLY*, clean it up
                    dicts = {}
                    for d in filter(lambda x:isinstance(x,dict),self.grammar[tag.name][0]):
                        dicts.update(d)
                    found = False
                    for key in dicts.keys():
                        if (isinstance(key, str) and key == item.name) \
                        or (isinstance(key, re._pattern_type) and key.search(item.name)):
                            item.name = dicts[key]
                            self.test(item, depth + 1)
                            found = True
                    if not found:
                        print "%s[%s] ******** meaningless in [%s] ********" % ((depth + 1) * '*', item.name, tag.name)
            elif isinstance(item, wmldata.DataText):
                if item.name in self.grammar[tag.name][1] or any(map(lambda x:(bool)(x.search(item.name)),filter(lambda x:isinstance(x,re._pattern_type),self.grammar[tag.name][1]))):
                    if self.verbosity > 2:
                        print "%s%s=\"%s\"" % ((depth + 1) * ' ', item.name, item.data)
                else:
                    print "%s%s=\"%s\" ******** meaningless in [%s] ********" % ((depth + 1) * '*', item.name, item.data, tag.name)
            else:
                raise Exception( "WTF we found something of class %s" % (item.__class__,) )


if __name__ == '__main__':
    import optparse, subprocess, os, codecs, sys

    # Ugly hack to force the output of UTF-8.
    # This prevents us from crashing when we're being verbose
    #  and encounter a non-ascii character.
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

    op = optparse.OptionParser()
    op.set_usage("Usage: %prog [options] [filename]")
    op.add_option("-p", "--path",
        help = "Specify Wesnoth's data dir.",
        dest = "path")
    op.add_option("-u", "--userpath",
        help = "Specify user data dir..",
        dest = "userpath")
    op.add_option("-v", "--verbose",
        action = "count",
        dest = "verbose",
        help = "Increase verbosity, 4 is the maximum.")
    op.add_option("-D", "--define",
        action = "append",
        dest = "defines",
        default = [],
        help = "Define (empty) preprocessor macros, for campaign/multiplayer inclusion.")
    (options, args) = op.parse_args()

    if not options.path:
        try:
            p = subprocess.Popen(["wesnoth", "--path"], stdout = subprocess.PIPE)
            path = p.stdout.read().strip()
            options.path = os.path.join(path, "data")
            sys.stderr.write("No Wesnoth path given.\nAutomatically found '%s'\n" % (options.path, ) )
        except OSError:
            options.path = '.'
            sys.stderr.write("Could not determine Wesnoth path.\nAssuming '%s'\n" % (options.path, ) )

    if len(args) < 1:
        args.append('%s/_main.cfg' % options.path)

    if options.verbose > 1:
        print "Options: %s\nArgs: %s\n"% (options, args)

    parser = wmlparser.Parser(options.path, options.userpath)

    if options.verbose > 3:
        parser.verbose = True

    if options.userpath:
        parser.parse_text("{~campaigns}")
    for file in args:
        parser.parse_file(file)
    for macro in options.defines:
        parser.parse_text("#define %s \n#enddef" % (macro, ) )

    data = wmldata.DataSub("WML")
    parser.parse_top(data)

    tester = Tester(data, options.verbose)
    tester.test()

# vim: tabstop=4: shiftwidth=4: expandtab: softtabstop=4: autoindent:
