"""
Creates the main java file. This creates a bogus main file
which creates several objects and calls some operations on them.
"""
import coral
from coral.lgen.codeartifact import CodeArtifact
import jhelp
import re


L = coral.meta.UML14

import create_static_class_structure

def create_main_java_class(all,
                           objects):
    e_class = L.Class(name = "main")
    e_op = L.Operation(name = "main",
                       ownerScope = "classifier",
                       owner = e_class)
    e_parameter = L.Parameter(name = "args",
                              behavioralFeature = e_op,
                              type = getattr(jhelp.java.lang, "String[]"))
    
    e_method = L.Method(specification = e_op,
                        name = "main",
                        owner = e_class,
                        ownerScope = "classifier")
    e_dep = L.Dependency()
    e_dep.client.add(e_class)

    body = ""
    _s = 0

    body += "\n/* Create all objects */\n"
    obj2name = {}
    for o in objects:
        assert len(o.classifier) == 1
        for tgt in o.classifier:
            e_dep.supplier.add(tgt)
        objname = "obj" + str(_s)
        _s += 1
        cname = jhelp.dot_name(o.classifier[0])
        body += cname + " " + objname + " = new " + cname + "();\n"

        obj2name[o] = objname

    body += "\n/* Add dummy method calls according to stimuluses */\n"

    def stimulus_sorter(x, y):
        """x and y are (integer tuple, stimulus, methodstring) )."""
        return cmp(x[0], y[0])

    stimuluses = all.select(lambda x: x.oclIsKindOf(L.Stimulus))
    ordered_stimuluses = []
    for s in stimuluses:
        assert s.receiver
        assert s.sender
        m = re.search("^\s*([\d\.]+)\s+([^\s]+)$", str(s.name))
        if not m:
            print "BAD STIMULUS", s.name
        assert m
        l = []
        for i in m.group(1).split("."):
            if i == "":
                continue
            l.append(int(i))
        ordered_stimuluses.append( ( tuple(l), s, m.group(2) ) )

    ordered_stimuluses.sort(stimulus_sorter)
    for i in ordered_stimuluses:
        body += obj2name[i[1].receiver] + "." + i[2] + ";\n"

    body += ""

    e_method.body.body = body
    all.add(e_method)
    all.add(e_dep)
    all.add(e_class)
    all.add(e_op)
    all.add(e_parameter)
    
    
