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

# -*- coding: UTF-8 -*-
#
# merge - script to merge several models into one file
#
# SYNOPSIS
#
# Explained in usage()
#
# DESCRIPTION
#
# merge combines several XMI files into one file. It can also
# follow href links to other projects and add them in as well;
# this is useful if a tool is unable to process cross-file
# XMI references.
#
# AUTHORS
#
# Marcus Alanen <maalanen@abo.fi> 2005
#

def main(arguments):
    def usage():
        print "Usage: merge [ --help | --version | [ --type xmitype ] [--follow] ]"
        print "             [-o outputfilename] filename..."
        print ""
        print "Options:"
        print "  --help         Display this information."
        print "  --version      Display version information and exit."
        print "  --type         Sets the XMI type of the output file."
        print "                 Possible values are 1.2 or 2.0."
        print "  --follow       Follow cross-file links to other projects."
        print "  -o file        Output filename, defaulting to standard output."
        print ""

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

    try:
        opts, args = getopt.getopt(arguments, "ho:", ["help", "version", "type=", "follow"])
    except getopt.GetoptError:
        import traceback
        traceback.print_exc()
        usage()
        sys.exit(2)

    opt_xmitype = "2.0"
    opt_follow = False
    opt_output = None

    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 ("--type"):
            opt_xmitype = a
        elif o in ("--follow"):
            opt_follow = True
        elif o in ("-o"):
            opt_output = a
        else:
            usage()
            sys.exit(2)

    import coral

    allP = []
    for f in args:
        p = coral.loadDocument(f)
        allP.append(p)
        
    if opt_follow:
        from coral.modeler.diagram.di_support import getAllLinkedProjects
        allP = getAllLinkedProjects(allP)

    res = coral.Project()
    res.setXMIFormat(opt_xmitype)

    for p in allP:
        for root in p.contents():
            root.__setProject__(res)
    if opt_output:
        res.setFilename(opt_output)
        coral.saveDocument(res)
    else:
        s = coral.saveDocument_str(res.contents(), res.getXMIFormat())
        sys.stdout.write(s)

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