# -*- coding: ISO-8859-1 -*-
""" capellaScript -- 04.03.2006 Andreas Herzog
>>> Strophentauscher

    Das Skript kann beliebige Strophen vertauschen.
    |
    
    |
    Version 1.0    |
    
    |
    

        |

<<<


"""

import xml.dom
import string
from xml.dom.minidom import NodeList

# doc = [] # parentNode von score

StrophenIterShow = ['1','2','3','4','5','6','7','8','9']
StrophenIter = ['0','1','2','3','4','5','6','7','8']

def latin1_e(u):
    return u.encode('Latin-1')
def latin1_d(u):
    return u.decode('Latin-1')
    
# neu eingefügt
def addElementNode(el,tagName):
    # add new Node to el if Node "tagName" does not exist
    # otherwise return the existing Node
    global doc
    childs = el.childNodes
    for n in range(childs.length):
        if childs[n].nodeType ==childs[n].ELEMENT_NODE and childs[n].tagName == tagName:
            return childs[n]
    newChild = doc.createElement(tagName)
    el.appendChild(newChild)
    return newChild
    
# neu eingefügt
def addNewElementNode(el,tagName):
    # add new Node with tagName "tagName" to el 
    global doc
    newChild = doc.createElement(tagName)
    el.appendChild(newChild)
    return newChild

def Test(text):
	messageBox('Test',str(text))
    
def getDialogValues():

    global  Auswahl, StropheA, StropheB


    rad1 = Radio(['nur Notenzeile mit Cursor', 'Notenzeile mit Cursor in allen Systemen   ','gesamte Partitur'], text='Zu bearbeiten:', padding = 0, value=1)
    StropheACombo = ComboBox(StrophenIterShow, padding = 0, value=0)
    StropheBCombo = ComboBox(StrophenIterShow, padding = 0, value=0)
    
    
    lab1 = Label('Tausche Strophe', width = 1)
    lab2 = Label('mit Strophe', width = 1)
	
    hbox01 = HBox([lab1, StropheACombo,lab2, StropheBCombo], padding = 2)
    
    vbox00  = VBox([hbox01,rad1], text='', padding=4)
    dlg = Dialog('Strophentauscher: ', vbox00)

    if dlg.run():
        Auswahl = rad1.value()
        StropheA = StropheACombo.value()
        StropheB = StropheBCombo.value()
        
        return True
    else:
        return False


def handleVoice(score, voice):
	global StropheA, StropheB
	
	for chord in voice.getElementsByTagName('chord'):
		for lyric in chord.getElementsByTagName('lyric'):
			for verse in lyric.getElementsByTagName('verse'):
				if verse.getAttribute('i') == StrophenIter[StropheA]:
					verse.setAttribute('i',StrophenIter[StropheB])
				elif verse.getAttribute('i') == StrophenIter[StropheB]:
					verse.setAttribute('i',StrophenIter[StropheA])

def getCursor():
    sel = curSelection()
    result = None
    if sel == 0:
        messageBox('Fehler', 'keine aktive Partitur')
        return result
    result = sel[0]
    return result
                        

def changeDoc(score):
    
    if getDialogValues():
	    		if Auswahl == 0:												# Nur die Markierte Zeile 
		        	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]]
		        		handleVoice(score, voice)
		        					
	    		if Auswahl > 0:												# Nur die Markierte Zeile, allerdings über die gesamte Partitur
		        	sel = getCursor()
		    		if sel == None:
		        		return
		    		else:
		        		system = score.getElementsByTagName('system')[sel[0]]
		        		staff = system.getElementsByTagName('staff')[sel[1]]
		        		actLayout = staff.getAttribute('layout')
		        		for staff in score.getElementsByTagName('staff'):
        					if (staff.getAttribute('layout') == actLayout) or (Auswahl == 2):
		        				for voice in staff.getElementsByTagName('voice'):
		        					handleVoice(score, voice)



# Hauptprogramm:

from caplib.capDOM import ScoreChange
import tempfile

class ScoreChange(ScoreChange):
	def changeScore(self, score):
	   global doc
	   doc = score.parentNode  
	   changeDoc(score)
		
        

if activeScore():
	
	activeScore().registerUndo("Strophen tauschen")
	tempInput = tempfile.mktemp('.capx')
	tempOutput = tempfile.mktemp('.capx')
	activeScore().write(tempInput)
	ScoreChange(tempInput, tempOutput)
	activeScore().read(tempOutput)
	os.remove(tempInput)
	os.remove(tempOutput)
