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

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


# Implementing NewPyImport
class PyImportDialog(ui.NewPyImport):
    """
    This dialog allows to add imports
    """
    @wxx.SetInfo(__doc__)
    def __init__(self, parent, container):
        """init method"""
        self._container = container
        super(PyImportDialog, self).__init__(parent)

    def CopyAttributes(self, _import):
        """Get the atributes"""
        _import._name = self._name
        _import._from = self._from
        _import._as = self._as or ''
        _import.note = self._note

    def SetAttributes(self, _import):
        """Set the attributes"""
        if _import._from:
            self.m_choicebook5.SetSelection(1)
            self.m_textCtrl821.SetValue(_import._name)
            self.m_comboBox12.SetValue(_import._from)
            if _import._as:
                self.m_checkBox1471.SetValue(True)
                self.m_textCtrl831.SetValue(_import._as)
                self.m_textCtrl831.Enable(True)
        else:
            self.m_choicebook5.SetSelection(0)
            self.m_textCtrl82.SetValue(_import._name)
            if _import._as:
                self.m_checkBox147.SetValue(True)
                self.m_textCtrl83.SetValue(_import._as)
                self.m_textCtrl83.Enable(True)
        self.m_richText3.SetValue(_import.note)

    def get_kwargs(self):
        """return arguments for object instance"""
        return  {'parent': self._container, 'name': self._name,
            'from': self._from, 'as': self._as,
            'note': self._note}

    def Validate(self):
        """Validate dialog"""
        index = self.m_choicebook5.GetSelection()
        name=r'[A-Za-z_][0-9A-Za-z_]*'
        if index == 0:
            #simple import
            self._name = self.m_textCtrl82.GetValue().strip()
            self._from = None
            if self.m_checkBox147.IsChecked():
                self._as = self.m_textCtrl83.GetValue().strip()
                if len(self._as) == 0:
                    wx.MessageBox("import alias must not be empty", "Error",
                        wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                    return False
                if re.match(r"^"+name+r"$", self._as) is None:
                    wx.MessageBox("import alias contains invalid characters", "Error",
                        wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                    return False
            else:
                self._as = None
        else:
            self._as = None
            self._name = self.m_textCtrl821.GetValue().strip()
            self._from = self.m_comboBox12.GetValue().strip()
            if len(self._from) == 0:
                wx.MessageBox("import element must not be empty", "Error",
                    wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                return False
            if re.match(r"^" + name + r"$", self._from) is None:
                wx.MessageBox("import element contains invalid characters", "Error",
                    wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                return False
            if self.m_checkBox1471.IsChecked():
                self._as = self.m_textCtrl831.GetValue().strip()
                if len(self._as) == 0:
                    wx.MessageBox("import alias must not be empty", "Error",
                        wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                    return False
                if re.match(r"^" + name + r"$", self._as) is None:
                    wx.MessageBox("import alias contains invalid characters", "Error",
                        wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                    return False
            else:
                self._as = None
        if len(self._name) == 0:
            wx.MessageBox("import name must not be empty", "Error",
                wx.OK | wx.CENTER | wx.ICON_ERROR, self)
            return False
        if re.match(r"^" + name + "(\." + name + ")*$", self._name) is None:
            wx.MessageBox("import name contains invalid characters", "Error",
                wx.OK | wx.CENTER | wx.ICON_ERROR, self)
            return False
        self._note = self.m_richText3.GetValue()
        return True

    # Handlers for NewMember events.
    def OnChangeFor(self, event):
        """Listbox selection"""
        self.m_comboBox12.AutoComplete(self._items)
        event.Skip()

    def OnKeyDown(self, event):
        """Listbox selection"""
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_UP or keycode == wx.WXK_NUMPAD_UP:
            txt = self.m_comboBox12.GetValue()
            i = self.m_comboBox12.FindString(txt)
            if i is not wx.NOT_FOUND and i > 0:
                self.m_comboBox12.SetSelection(i - 1)
        elif keycode == wx.WXK_DOWN or keycode == wx.WXK_NUMPAD_DOWN:
            txt = self.m_comboBox12.GetValue()
            i = self.m_comboBox12.FindString(txt)
            if i > wx.NOT_FOUND and i < len(self._items) - 1:
                self.m_comboBox12.SetSelection(i + 1)
        else:
            event.Skip()

    def OnAs(self, event):
        """Handle as checkbox"""
        self.m_textCtrl83.Enable(self.m_checkBox147.IsChecked())
        self.m_textCtrl831.Enable(self.m_checkBox1471.IsChecked())

    def OnFromChange(self, event):
        """from change method"""
        _from = self.m_textCtrl821.GetValue()
        # attempt to do the import and fill the combo
        self.m_comboBox12.Clear()
        m = self._container.inner_module
        if m is not None:
            module_dir = m.dir
        else:
            module_dir = None
        project_dir = self._container.project.dir
        import ostools
        s = ostools.import_dir(_from, module_dir, project_dir)
        if s:
            # avoid hidden symbols
            self._items = [x for x in s if x[0] != '_']
            self._items.sort()
            self.m_comboBox12.AppendItems(self._items)
        else:
            self._items = []

    def OnCancel(self, event):
        """cancel method"""
        self.EndModal(wx.ID_CANCEL)

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