#   Programmer:  Franz Steinhaeusler
#   E-mail:      francescoa@users.sourceforge.net
#   Note:        Initial Release 06/01/2004
#
#   Copyright 2005 Franz Steinhaeusler
#
#   Distributed under the terms of the GPL (GNU Public License)
#
#    DrPython is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#Plugin
#AutoSave

#Version: 0.0.0, 05.01.2005:


#todo option active/not active
import wx
import os
import time

def OnAbout(DrFrame):
    Version = "0.0.0"
    NameAndVersion = "AutoSave\nVersion: " + Version + "\n"
    AboutString = NameAndVersion + "By Franz Steinhaeusler\n\nReleased under the GPL."
    d = DrFrame.ShowMessage (AboutString, "About")

def OnHelp(DrFrame):
    d = DrFrame.ShowMessage ("AutoSave", "Help")


class AutoSavePrefsDialog(wx.Dialog):

    def __init__(self, parent, id):

        wx.Dialog.__init__(self, parent, id, "AutoSave", wx.Point(50, 50), \
                        wx.Size(300, 130), wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.THICK_FRAME | wx.RESIZE_BORDER)

        self.parent = parent
        self.chkautosaveactive = wx.CheckBox(self, -1, "AutoSave Active", pos = (20, 20))
        self.chkautosaveactive.SetValue(self.parent.AutoSave_AllowAutoSave)

        self.btnCancel = wx.Button(self, wx.ID_CANCEL, "&Close", size = (90, 23), pos = (20, 70))
        self.btnSave = wx.Button(self, wx.ID_OK, "&Save", size = (90, 23), pos = (140, 70))
        self.btnCancel.SetDefault()
        self.Bind(wx.EVT_BUTTON,  self.OnbtnClose, id = wx.ID_CANCEL)
        self.Bind(wx.EVT_BUTTON,  self.OnbtnSave, id = wx.ID_OK)
        self.chkautosaveactive.Bind(wx.EVT_CHECKBOX, self.OnChangeState)

    def OnbtnClose(self, event):
        self.EndModal(0)

    def OnChangeState(self, event):
        self.parent.AutoSave_AllowAutoSave = event.IsChecked()
        #print self.parent.AutoSave_AllowAutoSave
        event.Skip()

    def OnbtnSave (self, event):
        self.parent.AutoSave_AllowAutoSave = int(self.chkautosaveactive.GetValue())
        f = file(self.parent.pluginspreferencesdirectory + "/CleanUpFile.preferences.dat", 'w')
        f.write("<autosave.autosaveactive>" + str(self.parent.AutoSave_AllowAutoSave) + "</autosave.autosaveactive>\n")
        f.close()

def OnPreferences(DrFrame):
    d = AutoSavePrefsDialog(DrFrame, -1)
    d.ShowModal()
    d.Destroy()


def Plugin(DrFrame):

    self = DrFrame

    def OnActivate():
        if self.prefs.docautoreload and DrFrame.AutoSave_AllowAutoSave:
            x = 0
            oldpos = self.docPosition
            time.sleep(0.05)
            #wx.MilliSleep (50)
            reloaded = False
            for Document in self.txtDocumentArray:
                if Document.filename:
                    if not os.path.exists(Document.filename):
                        wx.MessageBox("File %s doesn't exist anymore! You could close it or save again!" % Document.filename, "On AutoReload", wx.ICON_EXCLAMATION)
                    else:
                    #Get Stat Info:
                        current_mtime = int(os.stat(Document.filename).st_mtime)

                        #Check Stat Info:
                        if Document.mtime > -1:
                            if current_mtime != Document.mtime:
                                if Document.GetModify():
                                    answer = wx.MessageBox('"%s" has been modified by an outside source.\nThe file is changed also.\n Best to not reload, save to another filename and then compare it.\nWould you like to reload?' \
                                        % (Document.filename), "Reload File?", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
                                else:
                                    answer = wx.MessageBox('"%s" has been modified by an outside source.  Would you like to reload?' % (Document.filename), "Reload File?", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
                                if answer == wx.OK:
                                    reloaded = True
                                    self.setDocumentTo(x)
                                    pos = self.txtDocument.GetCurrentPos()
                                    self.OpenFile(Document.filename, False)
                                    self.txtDocument.SetSelection(pos,pos)
                                else:
                                    Document.mtime = current_mtime
                                    self.setDocumentTo(oldpos)
                x += 1
            if reloaded:
                self.setDocumentTo(oldpos)
        #print "bef children"
        #for i in self.GetChildren():
            #print i
            #if isinstance (i, wx.Dialog):
                ##print "set", i
                ##i.SetFocus()
                #break

    def OnDeActivate():
        #print "ondeactivate"
        if DrFrame.AutoSave_AllowAutoSave:
            #promptonsaveall = DrFrame.prefs.promptonsaveall
            #DrFrame.prefs.promptonsaveall = False
            checksyntaxonsave = DrFrame.prefs.checksyntaxonsave
            DrFrame.prefs.checksyntaxonsave = False
            oldpos = self.docPosition
            x = 0
            for document in self.txtDocumentArray:
                if self.txtDocumentArray[x].GetModify():
                    if self.txtDocumentArray[x].filename:
                        self.SaveFile(x)
                x += 1
            self.setDocumentTo(oldpos)

            #DrFrame.OnSaveAll(None)
            #DrFrame.prefs.promptonsaveall = promptonsaveall
            DrFrame.prefs.checksyntaxonsave = checksyntaxonsave

    def OnMyActivate(event):
        #print self
        #print "act"
        if event.GetActive():
            #print "acta"
            OnActivate()
        else:
            OnDeActivate()
        event.Skip()

    def OnSwitchOffAutoSave (event):
        DrFrame.AutoSave_AllowAutoSave = False
        event.Skip()

    if os.path.exists(DrFrame.pluginspreferencesdirectory + "/AutoSave.preferences.dat"):
        f = file(DrFrame.pluginspreferencesdirectory + "/AutoSave.preferences.dat", 'r')
        text = f.read()
        f.close()
        DrFrame.AutoSave_Active = drPrefsFile.GetPrefFromText(DrFrame.AutoSave_Active, text, "autosave.autosaveactive", True)

    app = wx.GetApp()
    app.OnActivate = OnMyActivate
    DrFrame.AutoSave_AllowAutoSave = True
    DrFrame.OnSwitchOffAutoSave = OnSwitchOffAutoSave

    DrFrame.Bind(wx.EVT_CLOSE, DrFrame.OnSwitchOffAutoSave)

