import xml.etree.ElementTree as ElementTree
from xml.dom import minidom
import uuid as uuidly


def parsedoc(originFile, rueckmeldungen):
    try:
        xmldoc = minidom.parse(originFile)
        ruekm = "Auslesen der Datei"
        rueckmeldungen(ruekm)
        return xmldoc
    except FileNotFoundError:
        ruekm = "Datei nicht gefunden!\n"
        rueckmeldungen(ruekm)
    except Exception as e:
        ruekm = ("Datei konnte nicht gelesen werden!\nFehlermeldung:" + e.args[0] + "\n")
        rueckmeldungen(ruekm)
        
def parsetree(originFile):
    xmltree = ElementTree.parse(originFile)
    return xmltree


# ident = createId.createUuid()
def createIdent():
    ident = '{' + uuidly.uuid1().urn[9:] + '}'
    return ident


# verbindungen aufnehmen/sammeln  ...  collect conductor informatiions
def collect_conductors(xmldoc,cursor, connection, rueckmeldungen):
    conductorlist = xmldoc.getElementsByTagName('conductor')
    print('Collecting conductors')
    ruekm = "Verbindungen werden gesammelt"
    rueckmeldungen(ruekm)
    for s in conductorlist :
        try:
            if s.hasAttribute('element1') and s.hasAttribute('element2'):
                conductor = ([s.attributes['element1'].value,
                      s.attributes['terminal1'].value,
                      s.attributes['element2'].value,
                      s.attributes['terminal2'].value,
                      s.attributes['function'].value,
                      s.attributes['conductor_section'].value,
                      s.attributes['cable'].value,
                      s.attributes['conductor_color'].value,
                      s.attributes['bus'].value,
                      s.attributes['tension_protocol'].value])
                cursor.execute("INSERT INTO conductors VALUES (?,?,?,?,?,?,?,?,?,?)",
                               conductor[0::])
                connection.commit()
        except(IndentationError,TypeError) as e:
            print("Something went wrong!", e.args[0])
            ruekm = ("\nEtwas ist schiefgelaufen!" + e.args[0] + "\n")
            rueckmeldungen(ruekm)            


# Seiten aufnehmen/sammeln ... collect diagram informations
def collect_diagramms(xmldoc, cursor, connection,rueckmeldungen):
    diagramlist = xmldoc.getElementsByTagName('diagram')
    print('Collecting diagrams')
    ruekm = "Diagramme werden eingelesen"
    rueckmeldungen(ruekm)
    for diagram in diagramlist:
        try:
            diagramData = [diagram.attributes['folio'].value,
                diagram.attributes['plant'].value,
                diagram.attributes['locmach'].value,
                diagram.attributes['title'].value,
                diagram.attributes['date'].value,
                diagram.attributes['author'].value,
                diagram.attributes['indexrev'].value,
                int(diagram.attributes['order'].value),
                int(diagram.attributes['cols'].value),
                int(diagram.attributes['colsize'].value),
                int(diagram.attributes['rows'].value),
                int(diagram.attributes['rowsize'].value),
                diagram.attributes['displaycols'].value,
                diagram.attributes['displayrows'].value,
                diagram.attributes['titleblocktemplate'].value,
                diagram.attributes['titleblocktemplateCollection'].value,
                diagram.attributes['displayAt'].value,
                diagram.attributes['version'].value,
                diagram.attributes['auto_page_num'].value,
                diagram.attributes['freezeNewConductor'].value,
                diagram.attributes['freezeNewElement'].value,
                diagram.attributes['filename'].value]
            cursor.execute("""INSERT INTO diagrams VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                           diagramData[0::])
            connection.commit()
        except(IndentationError,TypeError) as e:
            print("Something went wrong!", e.args[0])
            ruekm = ("\nEtwas ist schiefgelaufen!" + e.args[0] + "\n")
            rueckmeldungen(ruekm)


# Bauteilinformationen und Verweise sammeln ... collect Elements and links
def collect_elements(xmldoc, cursor, connection, rueckmeldungen):
    print('Collecting elements and links')
    ruekm = "Elemente werden ausgelesen"
    rueckmeldungen(ruekm)
    try:
        num = 0
        diagramlist= xmldoc.getElementsByTagName('diagram')
        for diagram in diagramlist :
            num += 1
                   
            #Bauteileigenschaften    ...  element propertys
            for elements in diagram.childNodes:
                if elements.nodeName == "elements":
                    for element in elements.childNodes:
                        if element.nodeName == "element":
                            location = ""
                            function = ""
                            label = ""
                            plant = ""
#                             l_uuid = ""
                            elementData = [element.attributes['uuid'].value,
                                element.attributes['type'].value,
                                diagram.attributes['folio'].value,
                                element.attributes['x'].value,
                                element.attributes['y'].value]
                            for xx in element.childNodes:
                                if xx.nodeName == 'elementInformations':
                                    for elementinformation in xx.childNodes:
                                        if elementinformation.nodeName == "elementInformation":
                                            if elementinformation.hasChildNodes():
                                                if elementinformation.attributes['name'].value == "location":
                                                    location = elementinformation.firstChild.data.strip()
                                                if elementinformation.attributes['name'].value == "function":
                                                    function = elementinformation.firstChild.data.strip()
                                                if elementinformation.attributes['name'].value == "label":
                                                    label = elementinformation.firstChild.data.strip()
                                                if elementinformation.attributes['name'].value == "plant":
                                                    plant = elementinformation.firstChild.data.strip()
             
                                if xx.nodeName ==  "terminals":
                                    for terminal in xx.childNodes:
                                        if terminal.nodeName == 'terminal':
                                            terminalId = terminal.attributes['id'].value
                                            terminalData = [elementData[2], elementData[0], terminalId]
                                            cursor.execute("INSERT INTO elementTerminals VALUES(?,?,?)",
                                                             terminalData[0::])
                                            connection.commit()
    
                                if xx.nodeName == 'links_uuids':
                                    for link_uuid in xx.childNodes:
                                        if link_uuid.nodeName == 'link_uuid':
                                            linkData = [elementData[0], link_uuid.attributes['uuid'].value]
                                            cursor.execute("INSERT INTO elementLinks VALUES(?,?)",
                                            linkData[0::])
                                            connection.commit()

                            
                            elementData.insert(2, location)
                            elementData.insert(3, function)
                            elementData.insert(4, label)
                            elementData.insert(5, plant)
                            # we only want the name, not the path...
                            elementPath = elementData[1]
                            elementPathSplit = elementPath.split("/")
                            elementData[1] = elementPathSplit[-1]
                            cursor.execute("""INSERT INTO elements VALUES (?,?,?,?,?,?,?,?,?)""",
                                           elementData[0::])
                            connection.commit()
                                               

    except(IndentationError, TypeError) as e:
        print("Something went wrong!", e.args[0])
        ruekm = ("\nEtwas ist schiefgelaufen!" + e.args[0] + "\n")
        rueckmeldungen(ruekm)
        

def collect_elementTerminals(xmltree, cursor, connection, rueckmeldungen):
    print("Collecting embedded elements")
    ruekm = ("Eingebettete Elemente werden ausgelesen")
    rueckmeldungen(ruekm)
    try:
        tree = xmltree.getroot()
        collection = tree.find("collection")
        for e in collection:
            for element in list(e.iter("element")):
                embeddedElement = ["","","","","",""]
                embeddedElementTerminal = ["","","",""]
                embeddedElement[1] = element.get("name")
                for uuid in element.iter("uuid"):
                    embeddedElement[0] = uuid.get("uuid")
                    embeddedElementTerminal[3] = uuid.get("uuid")
                for definition in element.iter("definition"):
                    embeddedElement[2] = definition.get("type")
                    embeddedElement[3] = definition.get("link_type")
                for kindInformation in element.iter("kindInformation"):
                    embeddedElement[4] = kindInformation.get("name")
                    embeddedElement[5] = kindInformation.text
                for terminal in element.iter("terminal"):
                    embeddedElementTerminal[1] = terminal.get("name")
                    embeddedElementTerminal[0] = terminal.get("uuid")
                    embeddedElementTerminal[2] = terminal.get("type")
                    embeddedElementTerminal[3] = embeddedElement[1]
                    cursor.execute("""INSERT INTO embeddedElementTerminals VALUES(?,?,?,?)""",
                                   embeddedElementTerminal[0::])
                    connection.commit()
                cursor.execute("""INSERT INTO embeddedElements VALUES(?,?,?,?,?,?)""",
                               embeddedElement[0::])
            connection.commit()
    except(IndentationError,TypeError) as e:
        print("Something went wrong!", e.args[0])
        ruekm = ("\nEtwas ist schiefgelaufen!" + e.args[0] + "\n")
        rueckmeldungen(ruekm)
        
def diagramTemplate(xmltree):
    try:
        template = []
        tree = xmltree.getroot()
        newdiagrams = tree.find("newdiagrams")
        inset = newdiagrams.find("inset")
        template.append(inset.get("author"))
        template.append(inset.get("titleblocktemplate"))
        template.append(inset.get("titleblocktemplateCollection"))
        template.append(inset.get("displayAt"))
        return template
    except(IndentationError,TypeError) as e:
        print("Something went wrong!", e.args[0])
                                      
def newDiagram(xmltree):
    try:
        newDiagramData = []
        tree = xmltree.getroot()
        newdiagrams = tree.find("newdiagrams")    
        for propertys in newdiagrams.iter("property"):
            newDiagramData.append([propertys.get("name"), propertys.text])
        return newDiagramData        
    except(IndentationError,TypeError) as e:
        print("Something went wrong!", e.args[0])                            
                
                
                


# ------------------------------------------------------------------------------
# die Seite der Tabelle wird erstellt  ...  the page of a table is to be createt
# ------------------------------------------------------------------------------


def createCategory():
    category = ElementTree.Element("category", {"name":"Klemmenplaene"})
    names = ElementTree.SubElement(category, "names")
    name = ElementTree.SubElement(names, "name", {"lang":"de"})
    name.text = "Klemmenpläne"
    return category


def createPage(terminalStripNameP, pagenumberP, template, diagramData, dateP, part, identstr):
    qetElementName = "Klemmleiste " + terminalStripNameP + str(part) + ".elmt"
    qetElemtntTitle = "Klemmleiste " + terminalStripNameP + " / " + str(part)
    diagram = ElementTree.Element("diagram", {"order": str(pagenumberP), "displayAt":"bottom",
                                 "height":"1070", "colsize":"200", "displaycols":"true",
                                 "author": template[0], "plant":"", "rows":"6",
                                 "displayrows":"true",
                                 "title": qetElemtntTitle,
                                 "folio":"K" + str(pagenumberP), "rowsize":"175", "cols":"8",
                                 "freezeNewElement":"true", "filename":"", "version":"0.90",
                                 "freezeNewConductor":"false", "auto_page_num":"",
                                 "titleblocktemplateCollection":"embedded",
                                 "titleblocktemplate":template[1], "date": dateP,
                                 "indexrev":"", "locmach":"", })
    properties1 =ElementTree.SubElement(diagram, "properties")
    for i in diagramData[0::]:
        property1 = ElementTree.SubElement(properties1, "property", {"name":i[0], "show":"1"})
        property1.text = "V"

    defaultconductor = ElementTree.SubElement(diagram, "defaultcoductor", {"vertical-alignment":"AlignRight",
                                                    "onetextperfolio":"0",
                                                    "color2":"#000000", "horizontal-alignment":"AlignBottom",
                                                    "formula":"", "cable":"", "conductor_section":"",
                                                    "dash-size":"2", "horizrotatetext":"0",
                                                    "bicolor":"false", "conductor_color":"",
                                                    "vertirotatetext":"270", "displaytext":"1",
                                                    "function":"", "type":"multi", "bus":"",
                                                    "condsize":"1", "numsize":"7", "num":"",
                                                    "tension_protocol":"", "text_color":"#000000"})
    elements1 = ElementTree.SubElement(diagram, "elements")
    element1 = ElementTree.SubElement(elements1, "element", {"y":"30", "z":"10", "uuid": identstr,
                                                            "orientation":"0", "frezelabel":"true",
                                                        "x":"70", "prefic":"", "type":"embed://import/Klemmenplaene/" + qetElementName})
    terminals = ElementTree.SubElement(element1, "terminals")
    inputs = ElementTree.SubElement(element1, "inputs")
    elementInformations1 = ElementTree.SubElement(element1, "elementInformations")
    elementInformation1 = ElementTree.SubElement(elementInformations1, "elementInfomation")
    dynamic_texts = ElementTree.SubElement(element1, "dynamic_texts")
    texts_groups = ElementTree.SubElement(element1, "texts_groups")
    return diagram


# ------------------------------------------------------------------------------
# der Rahmen der Tabelle wird erstellt  ...  the frame of a table is to be createt
# ------------------------------------------------------------------------------


def createTable(terminalStripNameT, part, parts, identstr):
    qetElementName = "Klemmleiste " + terminalStripNameT + str(part) + ".elmt"
    qetElemtntTitle = "Klemmleiste " +terminalStripNameT + " / " + str(part)

    
    element = ElementTree.Element("element", {"name": qetElementName})
    definition = ElementTree.SubElement(element, "definition", {"link_type":"simple",
                                                    "hotspot_y":"10", "height":"1060",
                                                    "version":"0.90", "hotspot_x":"2",
                                                    "width":"1560", "type":"element"})
    uuid = ElementTree.SubElement(definition, "uuid", {"uuid":identstr})
    names = ElementTree.SubElement(definition, "names")
    name = ElementTree.SubElement(names, "name", {"lang":"de"})
    name.text = qetElemtntTitle
    elementInformatiions = ElementTree.SubElement(definition, "elementInformations")
    informations = ElementTree.SubElement(definition, "informations")
    informations.text = ""
    description = ElementTree.SubElement(definition, "description")

    # rectangles: 0 = pageframe, 1 = cablelistframe, 2 = chosenterminalframe, 3 = nameterminalstripframe
    # [y-pos, width, x-pos, height]
    rectangles = (["-5", "1555", "0", "1050"],
                  ["-5", "600", "0", "180"],
                  ["-5", "600", "955", "180"],
                  ["-5", "355", "600", "60"])
    for s in rectangles:
        rect = ElementTree.SubElement(description, "rect",
                                      {"y":s[0], "width":s[1], "antialias":"false",
                                       "ry":"0", "x":s[2], "rx":"0",
                                       "style":"line-style:normal;line-weight:normal;filling:none;color:black",
                                       "height":s[3]})
    # lines
    lines = (["15", "0", "600", "15", "thin"], # Unter Überschrift Kabelliste 
             ["35", "0", "600", "35", "thin"], # Zeilen Kabelliste
             ["55", "0", "600", "55", "thin"],
             ["75", "0", "600", "75", "thin"],
             ["95", "0", "600", "95", "thin"],
             ["115", "0", "600", "115", "thin"],
             ["135", "0", "600", "135", "thin"],
             ["155", "0", "600", "155", "thin"],
             ["242", "0", "1555", "242", "normal"], # Unter Überschrift Klemmentabelle 2 Linien
             ["245", "0", "1555", "245", "normal"],
             ["215", "60", "60", "1045", "normal"], # senkrechte Trennlinien
             ["215", "270", "270", "1045", "normal"],
             ["215", "560", "560", "1045", "normal"],
             ["215", "1000", "1000", "1045", "normal"],
             ["215", "1500", "1500", "1045", "normal"], 
             ["235", "90", "90", "1045", "thin"], # zwischenlinien Kabelzuordnung
             ["235", "120", "120", "1045", "thin"],
             ["235", "150", "150", "1045", "thin"],
             ["235", "180", "180", "1045", "thin"],
             ["235", "210", "210", "1045", "thin"],
             ["235", "240", "240", "1045", "thin"],
             ["235", "580", "580", "1045", "thin"],
             ["235", "690", "690", "1045", "thin"],
             ["235", "865", "865", "1045", "thin"],
             ["235", "980", "980", "1045", "thin"],
             ["235", "1290", "1290", "1045", "thin"],
             ["235", "1320", "1320", "1045", "thin"],
             ["235", "1350", "1350", "1045", "thin"],
             ["235", "1380", "1380", "1045", "thin"],
             ["235", "1410", "1410", "1045", "thin"],
             ["235", "1440", "1440", "1045", "thin"],
             ["235", "1470", "1470", "1045", "thin"],
             ["220", "765", "765", "1044", "hight"], # dicke linien an Klemmennummern
             ["220", "805", "805", "1044", "hight"],
             ["15", "955", "1555", "15", "normal"]) # unter Überschrift Rahmen verwendete Klemme
    for s in lines:
        line = ElementTree.SubElement(description, "line",
                                      {"y1":s[0],
                                       "style":f"line-style:normal;line-weight:{s[4]};filling:none;color:black",
                                       "Length1":"1.5", "x1":s[1], "end1":"none", "antialias":"false",
                                       "x2":s[2], "length2":"1.5", "y2":s[3], "end2":"none"})      
    text = ElementTree.SubElement(description, "text",
                                  {"font":"Sans Serif,28,-1,5,75,0,0,0,0,0",
                                   "rotation":"0", "y":"40", "color":"#000000",
                                   "x":"770", "text":terminalStripNameT}) # Rahmen 4 / Klemmleistenbezeichnung
    text = ElementTree.SubElement(description, "text",
                          {"font":"Sans Serif,9,-1,5,75,0,0,0,0,0",
                           "rotation":"0", "y":"80", "color":"#000000",
                           "x":"615", "text":"Blatt "+ str(part) + " von " + str(parts)}) # Blatt-NR / Anzahl Blätter 
    texts = (["9", "75", "15", "10", "Verwendete Kabel oder Einzelader:"], # Texte im Rahmen Kabelliste
             ["9", "50", "45", "30", "Bezeichnung         Ziehl                         Typ                     Querschnitt   Aderzahl   Spannung/Pot."],
             ["9", "75", "5", "50", "1"],
             ["9", "75", "5", "70", "2"],
             ["9", "75", "5", "90", "3"],
             ["9", "75", "5", "110", "4"],
             ["9", "75", "5", "130", "5"],
             ["9", "75", "5", "150", "6"],
             ["9", "75", "5", "170", "7"],
             ["9", "75", "615", "25", "Klemmleiste:"], # Überschrift
             ["9", "75", "970", "10", "Verwendete Klemme:                                                         Bemerkungen:"],
             ["9", "50", "10", "220", "Plan-"], # Spaltenüberschriften rechts
             ["9", "50", "10", "235", "verweis"],
             ["9", "75", "100", "215", "Kabel"],
             ["9", "50", "150", "215", "Ader-Nr.  /  Farbe"],
             ["9", "75", "72", "235", "1"], 
             ["9", "75", "102", "235", "2"],
             ["9", "75", "132", "235", "3"],
             ["9", "75", "162", "235", "4"],
             ["9", "75", "192", "235", "5"],
             ["9", "75", "222", "235", "6"],
             ["9", "75", "252", "235", "7"],
             ["9", "75", "395", "215", "Ziehl"],
             ["9", "50", "276", "235", "= Anlage   /   + Ort   /   - Bauteil   /   : Anschluss"],
             ["9", "50", "700", "235", "Funktion"],
             ["9", "50", "592", "235", "Brücke / Buchse"],
             ["11", "75", "755", "190", "Klemme"],
             ["9", "50", "813", "220", "Plan-"], # rechts
             ["9", "50", "813", "235", "verweis"],
             ["9", "50", "880", "235", "Brücke / Buchse"],
             ["9", "50", "1510", "220", "Plan-"],
             ["9", "50", "1510", "235", "verweis"],
             ["9", "75", "1117", "215", "Ziehl"],
             ["9", "50", "1005", "235", "= Anlage   /   + Ort   /   - Bauteil  /   : Anschluss"],
             ["9", "75", "1330", "215", "Kabel"],
             ["9", "50", "1380", "215", "Ader-Nr.  /  Farbe"],
             ["9", "75", "1302", "235", "1"], 
             ["9", "75", "1332", "235", "2"],
             ["9", "75", "1362", "235", "3"],
             ["9", "75", "1392", "235", "4"],
             ["9", "75", "1422", "235", "5"],
             ["9", "75", "1452", "235", "6"],
             ["9", "75", "1482", "235", "7"])
    for s in texts:
        text = ElementTree.SubElement(description, "text",
                                      {"font":f"Sans Serif,{s[0]},-1,5,{s[1]},0,0,0,0,0",
                                       "rotation":"0", "y":s[3], "color":"#000000",
                                       "x":s[2], "text":s[4]})
    return element


# --------------------------------------------------------------------------------
# Erstellen der Tabellenzeile ... create the tablecol
# --------------------------------------------------------------------------------


def createRowOuter(terminalpoint_obj,b,c,d):
    print(terminalpoint_obj.name, terminalpoint_obj.element, terminalpoint_obj.typ, "  ", c)
    print(c[0])
    cy = c[0].index(terminalpoint_obj.name)
#     print(cy)
    x = 240 + (b*20) + (cy*20)
    c = 0
    if terminalpoint_obj.cable != "":
        c =40
        for i in d:
            if terminalpoint_obj.cable != i[1]:
                c += 30
            else:
                break        
    description = ElementTree.Element("description")
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"8", "text":"/" + terminalpoint_obj.page + " ."
                               + terminalpoint_obj.y + terminalpoint_obj.x}) # Seitenverweis
    if terminalpoint_obj.cable != "":
        text = ElementTree.SubElement(description, "text",
                                  {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                                   "rotation":"0", "y":str(x), "color":"#000000",
                                   "x":str(c), "text":terminalpoint_obj.conductor_color})    
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"280", "text":terminalpoint_obj.plant})
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"355", "text":terminalpoint_obj.location})
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"425", "text":terminalpoint_obj.element})
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"515", "text":terminalpoint_obj.element_terminalpoint})
    return description


def createRowInner(terminalpoint_obj,b,c,d):
    print("interessant  ", terminalpoint_obj.name, "  ", terminalpoint_obj.element, "  ", terminalpoint_obj.typ, "  ", c)
    cy = c[1].index(terminalpoint_obj.name)
    print(cy)
    x = 240 + (b*20) + (cy*20)
    c = 0
    if terminalpoint_obj.cable != "":
        c = 1270
        for i in d:
            if terminalpoint_obj.cable != i[1]:
                c += 30
            else:
                break            
    description = ElementTree.Element("description")
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"1505", "text":"/"+ terminalpoint_obj.page +" ."
                               + terminalpoint_obj.y + terminalpoint_obj.x}) # Seitenverweis
    if terminalpoint_obj.cable != "":
        text = ElementTree.SubElement(description, "text",
                                  {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                                   "rotation":"0", "y":str(x), "color":"#000000",
                                   "x":str(c), "text":terminalpoint_obj.conductor_color})   
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"1010", "text":terminalpoint_obj.plant})
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"1085", "text":terminalpoint_obj.location})
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"1160", "text":terminalpoint_obj.element})
    text = ElementTree.SubElement(description, "text",
                              {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                               "rotation":"0", "y":str(x), "color":"#000000",
                               "x":"1250", "text":terminalpoint_obj.element_terminalpoint})
    return description

 
def createTerminal(Klemme,linepos, rows, klemmstellenName, function):
    x = 240 + (linepos*20 + (rows // 2 * 10))
    y = 220 + linepos*20
    
    description = ElementTree.Element("description")
    text = ElementTree.SubElement(description, "text",
                          {"font":"Sans Serif,11,-1,5,75,0,0,0,0,0",
                           "rotation":"0", "y":str(x), "color":"#000000",
                           "x":"772", "text":str(Klemme[1])})
    text = ElementTree.SubElement(description, "text",
                      {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                       "rotation":"0", "y":str(x), "color":"#000000",
                       "x":"810", "text":str("/" + Klemme[3] + " ." + Klemme[5] + str(Klemme[4]))})
    text = ElementTree.SubElement(description, "text",
                      {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                       "rotation":"0", "y":str(x), "color":"#000000",
                       "x":"700", "text":str(function)})
    z = 1
    for klemmpunk in klemmstellenName[0]:
        text = ElementTree.SubElement(description, "text",
                      {"font":"Sans Serif,9,-1,5,75,0,0,0,0,0",
                       "rotation":"0", "y":str(y + z *20), "color":"#000000",
                       "x":"565", "text":str(klemmpunk)})
        z += 1
    z = 1
    for klemmpunk in klemmstellenName[1]:
        text = ElementTree.SubElement(description, "text",
                      {"font":"Sans Serif,9,-1,5,75,0,0,0,0,0",
                       "rotation":"0", "y":str(y + z *20), "color":"#000000",
                       "x":"985", "text":str(klemmpunk)})
        z += 1   

    return description

def createBridge1(terminal, linepos, rows):
    y = 232 + (linepos*20 + (rows // 2 * 10))        
    return y, terminal.element, terminal.terminal


def createBridge2(bridge):
    if bridge.position == "inner":
        x = "965"
    if bridge.position == "outer":
        x = "595"
    endl = int(bridge.y_end)+8
    description = ElementTree.Element("description")
    line = ElementTree.SubElement(description, "line",
                              {"y1":str(bridge.y_start),
                               "style":"line-style:normal;line-weight:height;filling:black;color:black",
                               "length1":"4", "x1":str(x), "end1":str(bridge.start), "antialias":"false",
                               "x2":str(x), "length2":"4", "y2":str(endl), "end2":str(bridge.end)})
    return description


def createLines(linepos,rows):
    x = 245 + (linepos*20)
    description = ElementTree.Element("description")
    while rows > 1:
        line = ElementTree.SubElement(description, "line",
                              {"y1":str(x),
                               "style":"line-style:dashed;line-weight:thin;filling:none;color:black",
                               "Length2":"1.5", "x1":"0", "end1":"none", "antialias":"false",
                               "x2":"580", "length2":"1.5", "y2":str(x), "end2":"none"}) # Trennstrich gestrichelt
        line = ElementTree.SubElement(description, "line",
                              {"y1":str(x),
                               "style":"line-style:dashed;line-weight:thin;filling:none;color:black",
                               "Length2":"1.5", "x1":"980", "end1":"none", "antialias":"false",
                               "x2":"1555", "length2":"1.5", "y2":str(x), "end2":"none"}) # Trennstrich gestrichelt
        x += 20
        rows -= 1
    line = ElementTree.SubElement(description, "line",
                  {"y1":str(x),
                   "style":"line-style:normal;line-weight:normal;filling:none;color:black",
                   "Length2":"1.5", "x1":"0", "end1":"none", "antialias":"false",
                   "x2":"1555", "length2":"1.5", "y2":str(x), "end2":"none"}) # Trennstrich normal
    return description


def createCableListPart(a):
    y = 30
    description = ElementTree.Element("description")
    for i in a:
        y += 20
        text = ElementTree.SubElement(description, "text",
                                  {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                                   "rotation":"0", "y":str(y), "color":"#000000",
                                   "x":"50", "text":str(i[0])})
        text = ElementTree.SubElement(description, "text",
                                  {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                                   "rotation":"0", "y":str(y), "color":"#000000",
                                   "x":"140", "text":str(i[3])})
        text = ElementTree.SubElement(description, "text",
                                  {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                                   "rotation":"0", "y":str(y), "color":"#000000",
                                   "x":"385", "text":str(i[2])})
        text = ElementTree.SubElement(description, "text",
                                  {"font":"Sans Serif,9,-1,5,50,0,0,0,0,0",
                                   "rotation":"0", "y":str(y), "color":"#000000",
                                   "x":"540", "text":str(i[1])})
    return description


