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

#Plugin
#myProject

import wx
import drScrolledMessageDialog
from drSourceBrowser import drSourceBrowserPanel
import drPrefsFile
import os.path

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

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

History:
    0.0.1   22 Fev 2006
    0.0.2   10 Fev 2007
"""
    drScrolledMessageDialog.ShowMessage(DrFrame, HelpString, "Help")

def OnPreferences(DrFrame):
    DrFrame.ShowMessage("Nothing to configure ... ;)")

def Plugin(DrFrame):
    def myProject (event):
        if os.path.exists(myprefsfile):
            f = open(myprefsfile, 'r')
            s = f.readline()
            lastproject = s.rstrip()
            lastproject = s.split('/')[-1].split('.')[0]
            f.close()
        else:
            lastproject=None
        ID_SAVE = DrFrame.GetNewId() //wx.NewId()
        ID_LOAD = DrFrame.GetNewId() //wx.NewId()
        ID_LAST = DrFrame.GetNewId() //wx.NewId()
        menu = wx.Menu()
        menu.Append(ID_SAVE, "Save Project")
        DrFrame.Bind(wx.EVT_MENU, OnSaveProject, id=ID_SAVE)
        menu.Append(ID_LOAD, "Load Project")
        DrFrame.Bind(wx.EVT_MENU, OnLoadProject, id=ID_LOAD)
        if lastproject is not None:
            menu.Append(ID_LAST, "Load %s" %lastproject)
            DrFrame.Bind(wx.EVT_MENU, LoadLast, id=ID_LAST)
        (x,y) = DrFrame.ScreenToClient(wx.GetMousePosition())
        DrFrame.PopupMenu(menu, (x,y+40))
        menu.Destroy()


    def LoadLast(event):
        OnLoadProject(None,True)

    def OnLoadProject(event,default=False):
        try:
            projectfilename=''
            if default==False:
                dlg = wx.FileDialog(DrFrame, "Load Project", "", "", DrFrame.projectwildcard, wx.OPEN|wx.HIDE_READONLY)
                if DrFrame.ddirectory:
                    try:
                        d = DrFrame.ddirectory
                        dlg.SetDirectory(d)
                    except:
                        DrFrame.ShowMessage(("Error Setting Default Directory To: " + d), "DrPython Error")
                if dlg.ShowModal() == wx.ID_OK:
                    projectfilename = dlg.GetPath().replace("\\", '/')
                dlg.Destroy()
            else:
                f = open(myprefsfile, 'r')
                s = f.readline()
                projectfilename = s.rstrip()
                f.close()
            if os.path.exists(projectfilename)==False:
                return
            DrFrame.OnCloseAllDocuments(None)
            f = file(projectfilename, 'r')
            text = f.read()
            f.close()
            filenames = drPrefsFile.ExtractPreferenceFromText(text, "Files").rstrip().split('\n')
            #check for existing files
            if filenames and filenames[0] != '':
                fnames = []
                for i in range (len(filenames)):
                    if os.path.exists(filenames[i]):
                        fnames.append (filenames[i])
                    else:
                        ActiveDocument -= 1
                        DrFrame.ShowMessage("File does not exist: " + filenames[i], "Projects")
                filenames = fnames
                #Load the Files
                l = len(filenames)
                if l > 0 and len(filenames[0]) > 0:
                    old = DrFrame.txtDocument.filename
                    x = 1
                    if l > 1:
                        filename = filenames[0].replace("\\", "/")
                        DrFrame.OpenFile(filename, len(old) > 0)
                    while x < l:
                        filename = filenames[x].replace("\\", "/")
                        DrFrame.OpenFile(filename, True)
                        x = x + 1
                    if l <= 1:
                        filename = filenames[0].replace("\\", "/")
                        if old or DrFrame.txtDocument.GetModify():
                            DrFrame.OpenFile(filename, True)
                        else:
                            DrFrame.OpenFile(filename, False)
            else:
                DrFrame.ShowMessage("No File in Project: " + projectfilename, "Projects")
            ActiveDocument = 0
            DrFrame.documentnotebook.SetSelection (ActiveDocument)
            DrFrame.documentnotebook.SetTab()
            DrFrame.txtDocument.SetFocus()
            DrFrame.SetStatusText(projectfilename, 2)
            # Save Prefs
            f = open(myprefsfile, 'w')
            f.write(projectfilename + '\n')
            f.close()

        except :
            DrFrame.ShowMessage("Error Reading Project" , "Read Project Error")

    def OnSaveProject(event):
        dlg = wx.FileDialog(DrFrame, "Save Project As", "", "", DrFrame.projectwildcard, wx.SAVE|wx.OVERWRITE_PROMPT)
        if DrFrame.ddirectory:
            try:
                d = DrFrame.ddirectory
                dlg.SetDirectory(d)
            except:
                DrFrame.ShowMessage(("Error Setting Default Directory To: " + d), "DrPython Error")
        if dlg.ShowModal() == wx.ID_OK:
            projectfilename = dlg.GetPath().replace("\\", "/")
            try:
                f = file(projectfilename, 'w')
                f.write("<Files>")
                x = 0
                for document in DrFrame.txtDocumentArray:
                    if document.filename:
                        f.write(document.filename + '\n')
                f.write("</Files>\n")
                f.close()
                DrFrame.SetStatusText(projectfilename, 2)
                # Save Prefs
                f = open(myprefsfile, 'w')
                f.write(projectfilename + '\n')
                f.close()
            except:
                DrFrame.ShowMessage(("Error Saving: " + projectfilename), "DrPython Error")
            dlg.Destroy()

    #------------------------------------------------------------------------------------
    myprefsfile = DrFrame.pluginsuserdatadirectory + "/myproject.log"
    DrFrame.projectwildcard = "DrPython Project File (*.prj)|*.prj|All Files (*)|*"
    
    DrFrame.LoadPluginShortcuts('myProject')

    ID_MYPROJECT = DrFrame.GetNewId()
    DrFrame.programmenu.AppendSeparator()
    DrFrame.programmenu.Append(ID_MYPROJECT, "MyProject", " MyProject")
    DrFrame.Bind(wx.EVT_MENU, myProject, id=ID_MYPROJECT)
    DrFrame.AddPluginFunction("myProject", "myProject", myProject)

