# This file is part of the Coral project.
# Please read the copyright notice in the LICENSE file.

# -*- coding: UTF-8 -*-
#
# countelements - script to count the amount of elements in an XMI file
#
# SYNOPSIS
#
# Explained in usage()
#
# DESCRIPTION
#
# countelements is a simple script that counts the amount of model
# elements in the given files
#
# AUTHORS
#
# Marcus Alanen <maalanen@abo.fi> 2004
#

def countElements(element):
    """Counts the amount of elements in the given cone element.
    """
    return element.__getAllParts__().size()
   
def main(arguments):
    def usage():
        print "Usage: countelements [ --help | --version | [ --summary ] filename... ]"
        print "Options:"
        print "  --help         Display this information"
        print "  --version      Display version information and exit"
        print "  --summary      Display only a summary of the information"
        print ""
        print "The given filenames are loaded and the model element count for each file"
        print "is output. If --summary is given, the total amount of elements is output."
        print ""

    def version():
        import coral
        print "This is Coral version",coral.version, " (countelements script)"
        
    import sys
    import getopt

    try:
        opts, args = getopt.getopt(arguments, "h", ["help", "version", "summary"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    opt_summary = False
    
    for o,a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif o in ("--version"):
            version()
            sys.exit(0)
        elif o in ("--summary"):
            opt_summary = True
        else:
            usage()
            sys.exit(2)

    if len(args) < 1:
        usage()
        sys.exit(2)

    sum = 0
    res = []
    digits = 0
    import coral
    for xmifile in args:
        try:
            prj = coral.loadDocument(xmifile)
        except:
            continue
        n = 0
        for root in prj.contents():
            n += countElements(root)
        sum += n
        res.append((n, xmifile))
        digits = max(digits, len(str(n)))

    formatstr = "%" + str(digits + 1) + "s %s"
    if opt_summary:
        res.append((sum, "total"))
    for n, file in res:
        print formatstr % (n, file)

if __name__ == "__main__":
    import sys
    main(sys.argv[1:])
