"""Subclass of Locals, which is generated by wxFormBuilder."""
import wx
import wx.propgrid as pg
from activity.files.ui import ui as ui


# Implementing Locals
class Locals(ui.Locals):
    """Pane showing current local vars"""

    def __init__(self, parent, handler):
        """Initialize pane"""
        self._handler = handler
        super(Locals, self).__init__(parent)

    # Update data
    def UpdateData(self):
        """Update the threads info"""
        self.Freeze()
        self.m_locals.Clear()
        _locals = self._handler.locals
        # _locals is a dictionary. We have here some things to consider
        # a) since dictionnary are not an ordered set, if we simply insert
        #    values, we get erratic order between steps... we need to
        #    sort keys before
        keys = _locals.keys()
        keys.sort()
        for name in keys:
            value = _locals[name]
            self.AddProperty(name, value)
        self.Thaw()

    def AddProperty(self, name, value=wx.EmptyString, append_in=None):
        """Add a new property"""
        #print 'property:{name} = {value}'.format(name=name, value=value)
        t = type(value)
        if t in [dict, list, tuple]:
            prop = pg.NewStringProperty(name, name, '<composed>')
        else:
            try:
                svalue = str(value)
                prop = pg.NewStringProperty(name, name, svalue)
            except:
                print 'failed', value
                svalue = '<undisplayable>'
                prop = pg.NewStringProperty(name, name, svalue)
        if append_in:
            self.m_locals.AppendIn(append_in, prop)
        else:
            self.m_locals.Append(prop)
        self.m_locals.SetPropertyReadOnly(prop)
        if t is dict:
            keys = [str(x) for x in value]
            keys.sort()
            trans = dict([(str(x), x) for x in value])  # key translator
            for k in keys:
                self.AddProperty(k, value[trans[k]], prop)
            self.m_locals.Collapse(prop)
        elif t in [list, tuple]:
            values = list(value)
            values.sort()
            for k in values:
                try:
                    sk = str(k)
                    self.AddProperty(sk, wx.EmptyString, prop)
                except:
                    print 'failed', k
                    pass
            self.m_locals.Collapse(prop)


