#   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 OnHelp(DrFrame):
    HelpString = """myProject

History:
    0.0.1   22 Fev 2006
    0.0.2   10 Fev 2007
    0.0.3   03 Apr 2007 #Force extension to .prj
    0.0.4   05 Apr 2007 #history with last 10 projects
"""
    drScrolledMessageDialog.ShowMessage(DrFrame, HelpString, "Help")

class cfg(object): #Globals
    recentprojects=[]
    actualproject=""
    myprefsfile = ""
    projectwildcard = "DrPython Project File (*.prj)|*.prj|All Files (*)|*"

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


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

def Plugin(DrFrame):
    def myProject (event):
        ID_SAVE = DrFrame.GetNewId() //wx.NewId()
        ID_LOAD = DrFrame.GetNewId() //wx.NewId()
        ID_UPDATE = DrFrame.GetNewId() //wx.NewId()
        menu = wx.Menu()
        menu.Append(ID_LOAD, "Load Project")
        DrFrame.Bind(wx.EVT_MENU, OnLoadProject, id=ID_LOAD)
        menu.Append(ID_SAVE, "Save Project")
        DrFrame.Bind(wx.EVT_MENU, OnSaveProject, id=ID_SAVE)
        if len(cfg.actualproject):
            menu.AppendSeparator()
            menu.Append(ID_UPDATE, "Update %s" %cfg.actualproject.split('/')[-1].split('.')[0])
            DrFrame.Bind(wx.EVT_MENU, OnUpdateProject, id=ID_UPDATE)
        if len(cfg.recentprojects):
            menu.AppendSeparator()
            id=0
            for s in cfg.recentprojects:
                menu.Append(id, "Load %s" %s.split('/')[-1].split('.')[0])
                DrFrame.Bind(wx.EVT_MENU, OnRecentProject, id=id)
                id+=1

        (x,y) = DrFrame.ScreenToClient(wx.GetMousePosition())
        DrFrame.PopupMenu(menu, (x,y+40))
        menu.Destroy()

    def OnUpdateProject(event):
        auxSaveProject(cfg.actualproject)

    def OnRecentProject(event):
        id=event.GetId()
        OnLoadProject(None,cfg.recentprojects[id])

    def OnLoadProject(event,projectfilename=""):
        try:
            if projectfilename=="":
                dlg = wx.FileDialog(DrFrame, "Load Project", "", "", cfg.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()
            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:
                        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")
            DrFrame.documentnotebook.SetSelection (0)
            DrFrame.documentnotebook.SetTab()
            DrFrame.txtDocument.SetFocus()
            DrFrame.SetStatusText(projectfilename, 2)
            # Save Prefs
            f = open(cfg.myprefsfile, 'w')
            for s in cfg.recentprojects:
                f.write(s + '\n')
            f.close()
            cfg.actualproject=projectfilename
        except :
            DrFrame.ShowMessage("Error Reading Project" , "Read Project Error")

    def OnSaveProject(event):
        dlg = wx.FileDialog(DrFrame, "Save Project As", "", "", cfg.projectwildcard, wx.SAVE|wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            projectfilename = dlg.GetPath().replace("\\", "/")
            if projectfilename.endswith('.prj')==False: #AB: bug of drFileDialog
                projectfilename=projectfilename.split('.')[0]+'.prj'
                auxSaveProject(projectfilename)
            dlg.Destroy()

    def auxSaveProject(projectfilename):
        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)

        if cfg.recentprojects.__contains__(projectfilename):
            i=cfg.recentprojects.index(projectfilename)
            cfg.recentprojects.pop(i)
        cfg.recentprojects.insert(0,projectfilename)
        if len(cfg.recentprojects)>10:
            cfg.recentprojects.pop(-1)

        # Save Prefs
        f = open(cfg.myprefsfile, 'w')
        for s in cfg.recentprojects:
            f.write(str(s) + '\n')
        f.close()

    #------------------------------------------------------------------------------------
    cfg.myprefsfile = DrFrame.pluginsdatdirectory + "/myproject.log"
    if os.path.exists(cfg.myprefsfile):
        f = open(cfg.myprefsfile, 'r')
        for s in f:
            cfg.recentprojects.append(s.strip())
        f.close()

    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)
