#   Programmer:  Antonio Barbosa
#   E-mail:      ab@jn.pt
#   Note:        Initial Release 08 Fev 2007
#

#Plugin
#Epydoc

import wx
import drScrolledMessageDialog
import drPrefsFile
import os.path

def OnAbout(DrFrame):
    Version = "0.0.1"
    NameAndVersion = "Epydoc: " + Version + "\n"
    AboutString = NameAndVersion + "By Antonio Barbosa"
    drScrolledMessageDialog.ShowMessage(DrFrame, AboutString, "About")

def OnHelp(DrFrame):
    HelpString = """  Epydoc

Creates html documentation with epydoc.
Get epydoc at http://epydoc.sourceforge.net
After install, configure locations and options with [Options : plugin prefs]
"""
    drScrolledMessageDialog.ShowMessage(DrFrame, HelpString, "Help")

def OnPreferences(DrFrame):
    dlg = PrefsDialog(parent=DrFrame)
    dlg.ShowModal()
    dlg.Destroy()

def _getPreferences(DrFrame):
    epydoc_script = ""
    htmlpath=""
    options=""
    if os.path.exists(DrFrame.pluginspreferencesdirectory + "/Epydoc.preferences.dat"):
        HomeDir = DrFrame.pluginspreferencesdirectory + "/Epydoc.preferences.dat"
        f = file(HomeDir, 'r')
        text = f.read()
        f.close()
        htmlpath = drPrefsFile.ExtractPreferenceFromText(text, "Html.Path")
        options = drPrefsFile.ExtractPreferenceFromText(text, "Epydoc.Options")
        epydoc_script = drPrefsFile.ExtractPreferenceFromText(text, "Epydoc.Location")
        if os.path.exists(epydoc_script) != True:
            epydoc_script = ""
    return epydoc_script,htmlpath,options

def _setPreferences(DrFrame,EpydocLocation,HtmlPath,Options):
    HomeDir = DrFrame.pluginspreferencesdirectory + "/Epydoc.preferences.dat"
    f = file(HomeDir, 'w')
    f.write("<Epydoc.Location>" + EpydocLocation + "</Epydoc.Location>\n")
    f.write("<Html.Path>" + HtmlPath + "</Html.Path>\n")
    f.write("<Epydoc.Options>" + Options + "</Epydoc.Options>\n")
    f.close()

class PrefsDialog(wx.Dialog):
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
        self.parent=kwds["parent"]
        wx.Dialog.__init__(self, *args, **kwds)
        self.label_1 = wx.StaticText(self, -1, "Epydoc Path")
        self.edEpydocPath = wx.TextCtrl(self, -1, "", style=wx.NO_BORDER)
        self.btEpydocPath = wx.Button(self, -1, "...")
        self.label_2 = wx.StaticText(self, -1, "Html Path")
        self.edHtmlPath = wx.TextCtrl(self, -1, "", style=wx.NO_BORDER)
        self.btHtmlPath = wx.Button(self, -1, "...")
        self.label_3 = wx.StaticText(self, -1, "Epydoc Options")
        self.edOptions = wx.TextCtrl(self, -1, "", style=wx.NO_BORDER)
        self.btOk = wx.Button(self, -1, "OK")
        self.btDefault = wx.Button(self, -1, "Defaults")
        self.btCancel = wx.Button(self, -1, "Cancel")
        self.SetTitle("Epydoc Prefs")
        self.label_1.SetMinSize((80, -1))
        self.edEpydocPath.SetMinSize((300, -1))
        self.btEpydocPath.SetMinSize((40, -1))
        self.label_2.SetMinSize((80, -1))
        self.edHtmlPath.SetMinSize((300, -1))
        self.btHtmlPath.SetMinSize((40, -1))
        self.label_3.SetMinSize((80, -1))
        self.edOptions.SetMinSize((300, -1))
        V_sizer_1 = wx.BoxSizer(wx.VERTICAL)
        H_sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
        H_sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
        H_sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        H_sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
        H_sizer_1.Add(self.label_1, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 4)
        H_sizer_1.Add(self.edEpydocPath, 1, wx.ALL|wx.EXPAND, 4)
        H_sizer_1.Add(self.btEpydocPath, 0, wx.ALL|wx.ADJUST_MINSIZE, 4)
        V_sizer_1.Add(H_sizer_1, 0, wx.ALL|wx.EXPAND, 4)
        H_sizer_2.Add(self.label_2, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 4)
        H_sizer_2.Add(self.edHtmlPath, 1, wx.ALL|wx.EXPAND, 4)
        H_sizer_2.Add(self.btHtmlPath, 0, wx.ALL|wx.ADJUST_MINSIZE, 4)
        V_sizer_1.Add(H_sizer_2, 0, wx.ALL|wx.EXPAND, 4)
        H_sizer_3.Add(self.label_3, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 4)
        H_sizer_3.Add(self.edOptions, 1, wx.ALL|wx.EXPAND, 4)
        V_sizer_1.Add(H_sizer_3, 0, wx.ALL|wx.EXPAND, 4)
        H_sizer_4.Add((10, 4), 1, wx.ADJUST_MINSIZE, 0)
        H_sizer_4.Add(self.btOk, 0, wx.ALL|wx.ADJUST_MINSIZE, 4)
        H_sizer_4.Add(self.btDefault, 0, wx.ALL|wx.ADJUST_MINSIZE, 4)
        H_sizer_4.Add(self.btCancel, 0, wx.ALL|wx.ADJUST_MINSIZE, 4)
        H_sizer_4.Add((10, 4), 1, wx.ADJUST_MINSIZE, 0)
        V_sizer_1.Add(H_sizer_4, 1, wx.ALL|wx.EXPAND, 4)
        self.SetAutoLayout(True)
        self.SetSizer(V_sizer_1)
        V_sizer_1.Fit(self)
        V_sizer_1.SetSizeHints(self)
        self.Layout()
        self.btEpydocPath.Bind(wx.EVT_BUTTON, self.onbtEpydocPath)
        self.btHtmlPath.Bind(wx.EVT_BUTTON, self.onbtHtmlPath)
        self.btOk.Bind(wx.EVT_BUTTON, self.onbtOk)
        self.btDefault.Bind(wx.EVT_BUTTON, self.onbtDefault)
        self.btCancel.Bind(wx.EVT_BUTTON, self.onbtCancel)
        self.Bind(wx.EVT_CLOSE,self.onExit)
        epydoc_script,htmlpath,options=_getPreferences(self.parent)
        self.edEpydocPath.SetValue(epydoc_script)
        self.edHtmlPath.SetValue(htmlpath)
        self.edOptions.SetValue(options)

    def onExit(self, evt):
        self.Destroy()

    def onbtEpydocPath(self, event):
        dlg = wx.FileDialog(self, "Select Epydoc", "", "", "Python Source (*.py *.pyw)|*.py;*.pyw", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.edEpydocPath.SetValue(dlg.GetPath())
        dlg.Destroy()

    def onbtHtmlPath(self, event):
        dlg = wx.DirDialog(self, "Select Default Directory For Html Docs:", style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
        if dlg.ShowModal() == wx.ID_OK:
            self.edHtmlPath.SetValue(dlg.GetPath())
        dlg.Destroy()

    def onbtOk(self, event):
        EpydocLocation = self.edEpydocPath.GetValue()
        HtmlPath = self.edHtmlPath.GetValue()
        Options = self.edOptions.GetValue()
        _setPreferences(self.parent,EpydocLocation,HtmlPath,Options)
        self.Close()

    def onbtDefault(self, event):
        self.edOptions.SetValue('--html -v --docformat restructuredtext --parse-only')
        self.edEpydocPath.SetValue('C:/Python24/Scripts/epydoc.py')
        self.edHtmlPath.SetValue('./docs')

    def onbtCancel(self, event):
        self.Close()


def Plugin(DrFrame):

    def PromptAddLine(text):
        """Adds line+\n to end and shows it"""
        ro = DrFrame.txtPrompt.GetReadOnly()
        DrFrame.txtPrompt.SetReadOnly(0)
        if text.endswith('\n')==False:
            DrFrame.txtPrompt.AddEncodedText(text+'\n')
        else:
            DrFrame.txtPrompt.AddEncodedText(text)
        pos = DrFrame.txtPrompt.GetLength()
        DrFrame.txtPrompt.GotoPos(pos)
        DrFrame.txtPrompt.SetReadOnly(ro)

    def OnEpydocAll(event):
        epydoc_script,htmlpath,options=_getPreferences(DrFrame)
        if epydoc_script == "":
            wx.MessageBox("Location of Epydoc has not been set up.\nPlease set it up first.", "DrPython", wx.OK | wx.ICON_EXCLAMATION)
            return

        mainpanel = DrFrame.mainpanel
        if not mainpanel.PromptIsVisible:
            mainpanel.PromptIsVisible = True
            mainpanel.OnSize(None)
        PromptAddLine('\n------------------ EPYDOC ------------------------------------\n')
        PromptAddLine('epydoc_script: '+epydoc_script)
        PromptAddLine('options: '+options)
        PromptAddLine('htmlpath: '+htmlpath)
        PromptAddLine('------------------------------------------------------------------')
        wx.Yield()
        names=[]
        directory=''
        #for document in DrFrame.txtDocumentArray
        for x in range(len(DrFrame.txtDocumentArray)):
            filePath = DrFrame.getFilePath(DrFrame.txtDocumentArray[x].GetFilename())
            directory=filePath[0]
            PromptAddLine('---> %s' %filePath[1])
            names.append(filePath[1])
        if names==['Untitled ']:
            PromptAddLine('\n***NO MODULES!**')
            return
        executable = '%s --output  %s %s' %(epydoc_script,htmlpath,options)
        for name in names:
            executable+=' '+name
        PromptAddLine('---> %s' %executable)
        wx.BeginBusyCursor()
        from popen2 import popen4
        os.chdir(directory)
        stdout_and_stderr, child_stdin = popen4(executable)
        child_stdin.close()
        while True:
            output = stdout_and_stderr.readline()
            if not output:
                break
            PromptAddLine(output)
        wx.EndBusyCursor()
        PromptAddLine('\n**** OK ****')
        if htmlpath[0]=='.': #Relativ Path
            os.startfile('%s%s/index.html' %(directory,htmlpath)) # without dos box
        else:
            os.startfile('%s/index.html' %(htmlpath)) # without dos box

    #------------------------------------------------------------------------------------
    ID_EPYDOC = DrFrame.GetNewId()
    
    DrFrame.LoadPluginShortcuts('EpyDoc')
    
    DrFrame.programmenu.AppendSeparator()
    DrFrame.programmenu.Append(ID_EPYDOC, "Epydoc All", " Creates Documentation with Epydoc")
    #DrFrame.AddPluginFunction("Epydoc", "Epydoc", OnEpydocAll)
    DrFrame.Bind(wx.EVT_MENU, OnEpydocAll, id=ID_EPYDOC)
    DrFrame.AddPluginShortcutFunction("Epydoc", "Epydoc All", OnEpydocAll)
