#!/usr/bin/env python
#
# uml2java - Simple UML 1.4 to Java converter
#
# SYNOPSIS
#
# converter.py xmifile [ outputdir ]
#
# GOALS
#
# Converts class diagrams into java packages and classes
# The operations are "dummy", writing out what method was called.
#
# Converts collaboration diagrams
# This creates a main() method which creates the initial objects
# and does some kind of method calls on them. We'll see...
#
# AUTHORS
#
# Marcus Alanen 2005-06
#
#
#
import sys
import coral
import os

import fix_uml_model
import jhelp
import create_static_class_structure
import create_main

from coral.lgen.codeartifact import CodeArtifact
L = coral.meta.UML14

f = sys.argv[1]
if len(sys.argv) > 2:
    outputdir = sys.argv[2]
else:
    outputdir = "tmp"

prj = coral.loadDocument(f)

jhelp.ensure_dirs( [ outputdir ] )
os.chdir(outputdir)

F_elems = {}
ca_makefile = CodeArtifact()

F_elems[0] = ("makefile", [ ca_makefile ] )

all = coral.Set()
for root in prj.contents():
    if root.oclIsKindOf(L.root_ed):
        all.unionWith(root.__getAllParts__())

objects = all.select(lambda x: x.oclIsKindOf(L.Object))
create_main.create_main_java_class(all, objects)


fix_uml_model.fix(all)

### Ensure directories exist #############################################

def create_hierarchy(e):
    l = coral.Element__getParentsAndMyself__(e)
    jhelp.ensure_dirs( [ str(i.name) for i in l ] )

for e in all.select(lambda x: x.oclIsKindOf(L.Package)):
    create_hierarchy(e)

for e in all:
    if e.oclIsKindOf(L.Classifier):
        create_static_class_structure.create_class(F_elems, e)

### OUTPUT EVERYTHING ################################################

for k,v in F_elems.iteritems():
    fname, cas = v
    f = file(fname, "w")
    try:
        for ca in cas:
            ca.dump_fd(f)
    finally:
        f.close()
