import wx


class AutoHeightWrappedStaticText(wx.StaticText):
    """
    It's a travesty that this behaviour needs custom hacking, but... at least it works.
    """

    def __init__(self, *args, **kwargs):
        wx.StaticText.__init__(self, *args, **kwargs)
        self._unwrapped_text = None
        self._last_wrapped_text = None
        self._nest = False
        self.Bind(wx.EVT_SIZE, self._on_size, self)

    def _on_size(self, e: wx.SizeEvent):
        if not self._nest:
            self._nest = True
            try:
                current_text = self.GetLabelText()
                if self._last_wrapped_text != current_text:
                    self._unwrapped_text = current_text
                self.SetLabelText(self._unwrapped_text)
                self.Wrap(e.GetSize().GetWidth())
                self._last_wrapped_text = self.GetLabelText()
            finally:
                self._nest = False
        e.Skip()
