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

import re
import wx
import wxx
from activity.models.ui import ui as ui
import model
import app.resources as rc


# Implementing NewNamespace
class NamespaceDialog(ui.NewNamespace):
    """
    This dialog allows to setup a namespace container.
    """
    @wxx.SetInfo(__doc__)
    def __init__(self, parent, container):
        """Initialization"""
        super(NamespaceDialog, self).__init__(parent)
        self.container = container
        self.original = ""
        self.m_textCtrl2.SetFocus()
        self.m_sdbSizer2OK.SetDefault()
        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(rc.GetBitmap("namespace"))
        self.SetIcon(icon)

    def Validate(self):
        """Process OnOk event"""
        self._name = self.m_textCtrl2.GetValue()
        if len(self._name) == 0:
            wx.MessageBox("Namespace name must be non empty", "Error",
                wx.OK | wx.CENTER | wx.ICON_ERROR, self)
            return False
        if re.match("^[A-Za-z_][0-9A-Za-z_]*$", self._name) is None:
            wx.MessageBox("namespace name contains invalid characters", "Error",
                wx.OK | wx.CENTER | wx.ICON_ERROR, self)
            return False
        if self.original != self._name:
            if self._name in [x._name for x in self.container.top_namespaces]:
                wx.MessageBox("Namespace already exist", "Error",
                    wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                return False
        self._note = self.m_richText3.GetValue()
        return True

    def CopyAttributes(self, namespace):
        """Transfer attributes to namespace"""
        namespace._name = self._name
        namespace.note = self._note

    def SetAttributes(self, namespace):
        """Transfer attributes from existing constructor"""
        self._container = namespace.parent
        self._name = namespace._name
        self.original = namespace._name
        self._note = namespace.note
        self.m_textCtrl2.SetValue(self._name)
        self.m_richText3.SetValue(self._note)
        self.SetTitle("Edit namespace")

    def get_kwargs(self):
        """Return kwargs suitable for object creation"""
        kwargs = {}
        kwargs['parent'] = self.container
        kwargs['name'] = self._name
        kwargs['note'] = self._note
        return kwargs

    def OnOK(self, event):
        """On Ok"""
        if self.Validate():
            self.EndModal(wx.ID_OK)


