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

import os, wx, wxx, app
import app.resources as rc
from ctx import localcontext as context


# Implementing NewProject
class ProjectDialog(app.NewProject):
    """
    This dialog is the start point for a new project to
    be created. You  may select the target language and
    set his common options. The language may be set only
    before the project is created.
    """
    @wxx.SetInfo(__doc__)
    def __init__(self, parent, container=None):
        """Initialization"""
        super(ProjectDialog, self).__init__(parent)
        stdPaths = wx.StandardPaths.Get()
        self._container = container
        # if this project is inside workspace, the base
        # path must be determined by this workspace
        wk = container.workspace
        if wk is not None:
            self._base = wk._dir
            self.m_bpButton3.Enable(False)
            self.m_textCtrl9.SetEditable(False)
        else:
            self._base = stdPaths.GetDocumentsDir()
        self.m_textCtrl9.SetValue(self._base)
        self.app = context.app
        self._original = ""
        self._autodir = True
        self._veto = False
        self.m_textCtrl1.SetFocus()
        icon = wx.EmptyIcon()
        icon.CopyFromBitmap(rc.GetBitmap("project"))
        self.SetIcon(icon)

    def CopyAttributes(self, prj):
        """Update project attributes with dialog values"""
        sel = self.m_choicebook1.GetSelection()
        if sel == 0:
            prj._language = 'c++'
        if sel == 1:
            prj._language = 'python'
        prj._name = self._name
        prj._dir = self._dir
        prj._includeDir = self.m_textCtrl23.GetValue()
        prj._srcDir = self.m_textCtrl24.GetValue()
        prj._useMaster = self.m_checkBox52.GetValue()
        prj._masterInclude = self.m_textCtrl25.GetValue()
        prj._author = self.m_textCtrl251.GetValue()
        prj._date = self.m_datePicker1.GetValue().FormatISODate()
        if self.m_checkBox53.IsChecked():
            prj._license = self.m_choice16.GetStringSelection()
        else:
            prj._license = None
        prj._type = self.m_choice151.GetStringSelection()
        prj._version[0] = self.m_spinCtrl11.GetValue()
        prj._version[1] = self.m_spinCtrl21.GetValue()
        prj._version[2] = self.m_spinCtrl31.GetValue()
        prj._useMakefile = self.m_checkBox54.IsChecked()
        prj.note = self.m_richText13.GetValue()

    def SetAttributes(self, prj):
        """Set dialog attributes based on existing project"""
        if prj._language == 'c++':
            self.m_choicebook1.SetSelection(0)
        if prj._language == 'python':
            self.m_choicebook1.SetSelection(1)
        self._veto = True
        self.m_textCtrl1.SetValue(prj._name)
        self.m_textCtrl9.SetValue(prj._dir)
        self.m_textCtrl23.SetValue(prj._includeDir)
        self.m_textCtrl24.SetValue(prj._srcDir)
        self.m_checkBox52.SetValue(prj._useMaster)
        self.m_textCtrl25.Enable(prj._useMaster)
        self.m_textCtrl25.SetValue(prj._masterInclude)
        self.m_textCtrl251.SetValue(prj._author)
        date = wx.DateTime()
        date.ParseDate(prj._date)
        self.m_datePicker1.SetValue(date)
        if prj._license is not None:
            self.m_checkBox53.SetValue(True)
            self.m_choice16.SetStringSelection(prj._license)
        else:
            self.m_checkBox53.SetValue(False)
        self.m_choice151.SetStringSelection(prj._type)
        self.m_spinCtrl11.SetValue(prj._version[0])
        self.m_spinCtrl21.SetValue(prj._version[1])
        self.m_spinCtrl31.SetValue(prj._version[2])
        self.m_checkBox54.SetValue(prj._useMakefile)
        self.m_richText13.SetValue(prj.note)

        self._original = prj._name
        self.SetTitle("Edit project")

    def OnPageChanging(self, event):
        """Checks if language can be changed"""
        if self._veto:
            event.Veto()
        else:
            event.Skip()

    def OnChangeProjectName(self, event):
        """Process change text event"""
        if self._autodir:
            name = self.m_textCtrl1.GetValue()
            #create a custom subdirectory
            self.m_textCtrl9.SetValue(os.path.join(self._base, name))
            if self.m_checkBox52.GetValue():
                #replace master include
                name = name.replace(" ", "_")
                name += ".h"
                self.m_textCtrl25.SetValue(name)

    def OnChooseDir(self, event):
        """Launch subdialog for choosing dir"""
        dialog = wx.DirDialog(self, "Select directory",
            self.m_textCtrl9.GetValue(), wx.DD_DIR_MUST_EXIST)
        if dialog.ShowModal() == wx.ID_OK:
            self.m_textCtrl9.SetValue(dialog.GetPath())
            self._autodir = False

    def OnToggleMasterInclude(self, event):
        """Toggle using master include file"""
        if self.m_checkBox52.GetValue():
            self.m_textCtrl25.Enable(True)
            self.m_textCtrl25.SetValue(self.m_textCtrl1.GetValue() + ".h")
        else:
            self.m_textCtrl25.Enable(False)

    def Validate(self):
        """Validate dialog"""
        sel = self.m_choicebook1.GetSelection()
        if sel == 0:
            self._language = 'c++'
        if sel == 1:
            self._language = 'python'
        self._name = self.m_textCtrl1.GetValue()
        self._dir = self.m_textCtrl9.GetValue()
        if len(self._name) == 0:
            wx.MessageBox("Project name must be non empty", "Error",
                wx.OK | wx.CENTER | wx.ICON_ERROR, self)
            return False
        if not self._original == self._name:
            if self.app.ExistProject(self._name) is True:
                wx.MessageBox("Project already exist", "Error",
                    wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                return False
        if len(self._dir) == 0:
            wx.MessageBox("Target directory must be non empty",
                "Error", wx.OK | wx.CENTER | wx.ICON_ERROR, self)
            return False
        if self.m_checkBox52.GetValue():
            if len(self.m_textCtrl25.GetValue()) == 0:
                wx.MessageBox("Master include must be non empty",
                    "Error", wx.OK | wx.CENTER | wx.ICON_ERROR, self)
                return False
        self._includeDir = self.m_textCtrl23.GetValue()
        self._srcDir = self.m_textCtrl24.GetValue()
        self._useMaster = self.m_checkBox52.GetValue()
        self._masterInclude = self.m_textCtrl25.GetValue()
        self._author = self.m_textCtrl251.GetValue()
        self._date = self.m_datePicker1.GetValue().FormatISODate()
        self._license = self.m_choice16.GetStringSelection()
        self._type = self.m_choice151.GetStringSelection()
        self._version = []
        self._version = [
            self.m_spinCtrl11.GetValue(),
            self.m_spinCtrl21.GetValue(),
            self.m_spinCtrl31.GetValue()]
        self._useMakefile = True
        return True

    def get_kwargs(self):
        """returns arguments for instance... pending"""
        kwargs = {
            'parent': self._container,
            'language': self._language,
            'name': self._name,
            'dir': self._dir,
            'includedir': self._includeDir,
            'sourcedir': self._srcDir,
            'usemaster': self._useMaster,
            'masterinclude': self._masterInclude,
            'author': self._author,
            'date': self._date,
            'license': self._license,
            'type': self._type,
            'version': self._version,
            'usemakefile': self._useMakefile
        }
        return kwargs

    # Handlers for NewProject events.
    def OnOK(self, event):
        """Handle ok button"""
        if self.Validate():
            self.EndModal(wx.ID_OK)


