#
# encoding: ISO-8859-15
#
# Represents slot primitive values textually
# from/to an external text editor
#

import re
import string

import coral
from coral.util.text_editor import TextualEditor

def private_property_sorter(x, y):
    return cmp(x.getName(), y.getName())

class EditAllSlotsEditor(TextualEditor):
    def __init__(self, element):
        self.__element = element
        TextualEditor.__init__(self, None)
        
    def __encodeSlotValue(self, v):
        """This should encode slot values suitable."""
        pass

    def __decodeSlotValue(self, v):
        """This should decode the slot value from the editor."""
        pass

    def _get(self):
        t = self.__element.__type__()
        l = []
        props = [ p for p in t.__properties__() ]
        props.sort(private_property_sorter)
        for p in props:
            if not p.getTarget().isDatatypeDefinition():
                continue
            pn = p.getName()
            s = self.__element.__getSlotByName__(pn)
    
            # Output UTF-8
            for i in s:
                l.append("%s: %s" % (pn, unicode(i).encode("UTF-8")))
        return l;

    def _set(self, stringlist):
        already_reset = {}
        t = self.__element.__type__()
        for s in stringlist:
            if not s:
                continue
            if s[0] == '#':
                continue
            i = s.find(": ") # obligatory space, removed
            if i == -1:
                continue
            slotname = s[:i].strip()
            value = s[i+2:].rstrip()
            # Assume input is UTF-8
            if isinstance(value, str):
                value = unicode(value, "UTF-8")

            if isinstance(slotname, unicode):
                slotname = slotname.encode("UTF-8")

            try:
                slot = self.__element.__getSlotByName__(slotname)
            except RuntimeError,e: # Catch coral::bad_slot
                continue
            #print "Doing slot", slot.getProperty().getName()
    
            p = slot.getProperty()
            tgt = p.getTarget()
            if not tgt.isDatatypeDefinition():
                continue
    
            try:
                if tgt == coral.Integer:
                    value = int(value)
                elif tgt == coral.Double:
                    value = double(value)
            except ValueError:
                # BUG display error and continue
                continue
    
            is_at_most_one = p.isAtMostOne()
            if not is_at_most_one and slot not in already_reset:
                already_reset[slot] = True
                slot.resetSlot()
    
            if is_at_most_one:
                setattr(self.__element, slotname, value)
            else:
                slot.append(value)

if __name__ == "__main__":
    import coral
    L = coral.lang.SMD01
    
    m = L.Property()
    
    m.name = "hello åbo"

    EditAllSlotsEditor(m)
