"""Some helper stuff for Java handling."""

import coral
import os
import re

uml2java_version = coral.version

### Some helpers ########################################################

def visibility_u2j(v):
    """Converts a UML 1.4 visibility string to its java equivalent."""
    return str(v) + " "

class Creator:
    """Stupid "bunch" class which just can be used to contain anything"""
    def __init__(self):
        pass

def dot_name(e):
    c = e.taggedValue.select(lambda x: x.name == "name")
    if c:
        return c[0].dataValue
    l = coral.Element__getParentsAndMyself__(e)
    s = ".".join( [ str(i.name) for i in l ] )
    return s

def find(e, s):
    l = s.split(".")
    for i in l:
        e = e.ownedElement.select(lambda x: x.name == i)[0]
    return e

def ensure_dirs(dir_list):
    s = ""
    for i in dir_list:
        s += i
        try:
            os.mkdir(s)
        except OSError,e:
            if str(e).find("File exists:") != -1:
                pass
            else:
                raise
        s += os.sep

def _remove_empty_prefix_strings(l):
    res = []
    start = True
    for i in l:
        if start and not i:
            continue
        start = False
        res.append(i)
    return res

def add_comment(ca, comment_elems):
    l = []
    for e in comment_elems:
        m = unicode(e).split("\n")
        for s in m:
            l.append(s.rstrip())
        
    if not l:
        return

    l = _remove_empty_prefix_strings(l)
    l.reverse()
    l = _remove_empty_prefix_strings(l)
    l.reverse()
        
    for i, c in enumerate(l):
        s = " * " + c
        s = re.sub("\*\/", "* /", s)
        l[i] = s

    l.insert(0, "/**")
    l.append(" **/")

    for i in l:
        ca.add(i)

# The +1 blessed greased fake Java environment in UML

java = coral.loadDocument("java.xmi").contents()[0]
#java_lang_Object = find(java, "lang.Object")
#java_util_Vector = find(java, "util.Vector")
#java_util_TreeSet = find(java, "util.TreeSet")
#java_lang_String_ARR = find(java, "lang.String[]")
#java_lang_void = find(java, "lang.void")
