import coral
import os

from coral.util.user import getUserHome

def install_SMD_language(language):
    assert  language.oclIsKindOf(coral.meta.SMD01.Language)
    assert (str(language.name)!="")
    name=str(language.name)+str(language.version)+str(language.revision)

    try:
        os.mkdir(getUserHome()+"/.coral/coral/lang/"+name)
        os.mkdir(getUserHome()+"/.coral/coral/lang/"+name+"/def")
    except:
        pass

    fname = getUserHome()+"/.coral/coral/lang/"+name+"/manifest.txt"
    fd=open(fname, "w")
    fd.write("name "+str(language.name)+"\n")
    fd.write("version "+str(language.version)+"\n")
    fd.write("revision "+str(language.revision)+"\n")
    fd.write("file def/"+name+".xmi\n")
    fd.write("xmlns "+str(language.URInamespace)+"\n")
    fd.close()
    
    oldPrj=language.__getProject__()

    try:
        newPrj=coral.Project()
        language.__setProject__(newPrj)
        xmifname = getUserHome()+"/.coral/coral/lang/"+name+"/def/"+name+".xmi"
        newPrj.setFilename(xmifname)
        newPrj.saveToDocument()

        coral.addXMLNSRmap(str(language.URInamespace),
                           str(xmifname),
                           str(language.name),
                           int(language.version),
                           int(language.revision))
    finally:
        language.__setProject__(oldPrj)

    
