# -*- coding: ISO-8859-1 -*-
""" capellaScript -- (c) Paul Villiger
>>> Tiny_XML
    
<<<

History:  22.12.03 - Erste Ausgabe
          07.01.04 - kein Absturz bei Umlauten
                    
"""


from xml.dom.minidom import parseString, NodeList, Node, Element
from string import find, replace
from binascii import hexlify

def latin1_e(u):
    return u.encode('Latin-1')

def getCursor():
    sel = curSelection()
    result = None
    if sel == 0:
        messageBox('Fehler', 'keine aktive Partitur')
        return result
    #if sel[0] != sel[1]:
    #    messageBox('Fehler', 'Markierung ist nicht leer')
    #    return result
    result = sel[0]
    return result

def getElementObjects(objList):  # returns a List
    newList = NodeList()
    for n in range(objList.length):
        if objList[n].nodeType == objList[n].ELEMENT_NODE:
            newList.append(objList[n])
    return newList


def changeDoc(score):
    sel = getCursor()
    if sel == None:
        #
        return
    else:
        system = score.getElementsByTagName('system')[sel[0]]
        staff = system.getElementsByTagName('staff')[sel[1]]
        voice = staff.getElementsByTagName('voice')[sel[2]]
        noteObject = voice.getElementsByTagName('noteObjects')[0]
        objList = getElementObjects(noteObject.childNodes)
        if objList.length <= sel[3]:
            return
        obj = objList[sel[3]]

        dom = parseString("<tinyXML></tinyXML>")
        newDoc = dom.documentElement
    
        newDoc.appendChild(obj)
        xmlString = newDoc.toprettyxml('      ','\n')
        n = 0
        search = chr(9)+'\n'
        while find(xmlString,search) <> -1:
            xmlString = replace(xmlString,search,'\n')
        search = chr(32)+'\n'
        while find(xmlString,search) <> -1:
            xmlString = replace(xmlString,search,'\n')
            
        xmlString = replace(xmlString,'\n\n','\n')
        xmlString = replace(xmlString,'\n\n','\n')
        messageBox('Tiny_XML',latin1_e(xmlString))

# Hauptprogramm:

from caplib.capDOM import ScoreChange
import tempfile

class ScoreChange(ScoreChange):
    def changeScore(self, score):
        changeDoc(score)

if activeScore():
    tempInput = tempfile.mktemp('.capx')
    tempOutput = tempfile.mktemp('.capx')
    activeScore().write(tempInput)
    
    ScoreChange(tempInput, tempOutput)

    os.remove(tempInput)
    os.remove(tempOutput)

