"""
Capitalize words of "name=*" tags in JOSM of selected primitives.
"""

from javax.swing import JOptionPane
from org.openstreetmap.josm import Main
from org.openstreetmap.josm.command import ChangePropertyCommand
from org.openstreetmap.josm.command import SequenceCommand

def getMapView():
    if Main.main and Main.main.map:
        return Main.main.map.mapView
    else:
        return None

prepositions = [" di ", " del ", " della ", " delle "]

commands = []
names = {}
mv = getMapView()
if mv == None:
    JOptionPane.showMessageDialog(Main.parent, "Please, open some data.")
else:
    if mv and mv.editLayer and mv.editLayer.data:
        #Get selected elements
        dataset = mv.editLayer.data
        elements = dataset.getSelected()
        if len(elements) == 0:
            JOptionPane.showMessageDialog(Main.parent, "Please, select some data.")
        else:
            #For each OSM object in the dataset
            for element in elements:
                tags = element.getKeys()
                if len(tags) != 0:
                    if "name" in tags:
                        #capitalize words of "name" value
                        oldName = element.get("name")
                        newName = oldName.title()
                        #exclude prepositions from capitalization
                        for prep in prepositions:
                            newName = newName.replace(prep.title(), prep.lower())
                        #change element tags
                        command = ChangePropertyCommand(element, "name", newName)
                        commands.append(command)
                        #remember changed names
                        if oldName != newName:
                            names[oldName] = newName
                            
            #Execute commands
            if len(commands) > 0:
                sequenceCommand = SequenceCommand("Updating properties of up to %s object" % len(commands), commands)
                Main.main.undoRedo.add(sequenceCommand)

            #Print some info
            if len(names) > 0:
                text = "Changed names:"
                for old, new in names.iteritems():
                    text += "\n%s --> %s" % (old, new)
            else:
                text = "No name has been changed."
            JOptionPane.showMessageDialog(Main.parent, text)
