"""Native exit dropdown inside the client, without a separate dialogue."""
import wx


class ExitChoicePopup(wx.ComboBox):
    def __init__(self, entry, exits, on_close):
        super().__init__(entry.Parent, choices=list(exits),
                         pos=entry.GetPosition(), size=entry.GetSize(),
                         style=wx.CB_READONLY | wx.TE_PROCESS_ENTER, name='')
        self._options = tuple(exits)
        self._selected_index = None
        self._finishing = False
        self._on_close = on_close
        self.SetSelection(0)
        self.Bind(wx.EVT_KEY_DOWN, self.on_key)
        self.Bind(wx.EVT_COMBOBOX, self.on_selection)
        self.Bind(wx.EVT_COMBOBOX_CLOSEUP, self.on_closeup)
        self.Bind(wx.EVT_TEXT_ENTER, self.on_confirm)
        wx.CallAfter(self.open_list)

    def open_list(self):
        if self and not self._finishing:
            self.SetFocus()
            self.Popup()

    def on_key(self, event):
        if not event.ControlDown() and not event.AltDown():
            code = event.GetKeyCode()
            if code in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
                self._finish(wx.ID_OK)
                return
            if code == wx.WXK_ESCAPE:
                self._finish(wx.ID_CANCEL)
                return
        event.Skip()

    def on_selection(self, event):
        self._finish(wx.ID_OK, event.GetSelection())

    def on_closeup(self, event):
        if not self._finishing:
            self._finish(wx.ID_CANCEL)
        event.Skip()

    def on_confirm(self, event):
        self._finish(wx.ID_OK)

    def _finish(self, result, index=None):
        if self._finishing:
            return
        if result == wx.ID_OK:
            if index is None:
                index = self.GetCurrentSelection()
            if not 0 <= index < len(self._options):
                return
            self._selected_index = index
        self._finishing = True
        wx.CallAfter(self._complete, result)

    def _complete(self, result):
        if not self:
            return
        selected = self.selected_exit() if result == wx.ID_OK else None
        self.Dismiss()
        self.Hide()
        self.Destroy()
        self._on_close(selected)

    def selected_exit(self):
        index = self._selected_index
        if index is None:
            index = self.GetCurrentSelection()
        return self._options[index] if 0 <= index < len(self._options) else None
