"""Subclass of NewEnumItem, which is generated by wxFormBuilder."""

import re
import wx
import wxx
from activity.models.ui import ui as ui


# Implementing NewEnumItem
class EnumItemDialog(ui.NewEnumItem):
    """
    This dialog allows to edit enum item.
    You can set an item explicit value or
    leave it blank for default value.
    """
    @wxx.SetInfo(__doc__)
    def __init__(self, parent, item=None):
        """Initialise dialog"""
        super(EnumItemDialog, self).__init__(parent)
        if item is not None:
            self.m_textCtrl56.SetValue(item[0])
            if len(item[1].strip()) > 0:
                self.m_comboBox6.Append(item[1])
            i = self.m_comboBox6.FindString(item[1].strip())
            self.m_comboBox6.SetSelection(i)
        self.origin = item
        self.parent = parent

    #Validate dialog
    def Validate(self):
        """Get values and validate"""
        self._label = self.m_textCtrl56.GetValue().strip()
        self._value = self.m_comboBox6.GetValue().strip()
        if not len(self._label):
            wx.MessageBox("enum item label must be not empty", "Error",
                wx.OK | wx.CENTER | wx.ICON_ERROR, self)
            return False
        if re.match("^[A-Za-z_][0-9A-Za-z_]*$", self._label) is None:
            wx.MessageBox("enum item label contains invalid characters", "Error",
                wx.OK | wx.CENTER | wx.ICON_ERROR, self)
            return False
        if len(self._value) and not re.match("^[0-9]*$", self._value):
            y = wx.MessageBox("enum item value is not a number. You are sure?", "Warning",
                wx.YES_NO | wx.CENTER | wx.ICON_ERROR, self)
            if y != wx.YES:
                return False
        if not self.origin or self.origin[0] != self._label:
            if self.parent.m_listCtrl5.FindItem(wx.NOT_FOUND, self._label) != wx.NOT_FOUND:
                wx.MessageBox("the item {} already exists".format(self._label), "Error",
                    wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                return False
        return True

    # Handlers for NewEnumItem events.
    def OnCancel(self, event):
        """Process cancel"""
        self.EndModal(wx.ID_CANCEL)

    def OnOK(self, event):
        """Process ok"""
        if self.Validate():
            self.EndModal(wx.ID_OK)
