#   Programmer: limodou
#   E-mail:     limodou@gmail.com
#
#   Copyleft 2005 limodou
#
#   Distributed under the terms of the GPL (GNU Public License)
#
#   NewEdit 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

import wx
import sys
import os.path
import EasyUtils
import getopt
import os.path
import traceback

__appname__ = 'EasyGui'
__author__ = 'limodou'
__version__ = '0.1'

class wxApp(wx.App):
    def OnInit(self):
        return True

class EasyCommander:
    def __init__(self, inline=True):
        self.inline = False #indicate that EasyCommnader is in other apps
        
    def run(self):
        self.initlog()
        self.processCommandLineArguments()
        self.wxApp = wxApp(0)
        mod = self.getPageModule()
        self.values = None
        
        #read config information from imported template module
        if hasattr(mod, 'scriptfile'):
            self.scriptfile = mod.scriptfile
        elif hasattr(mod, 'inipickle'):
            self.inipickle = mod.inipickle
        elif hasattr(mod, 'picklefile'):
            self.picklefile = mod.picklefile
        if self.picklefile:
            try:
                f = file(self.picklefile)
                import pickle
                self.values = pickle.load(f)
                f.close()
            except:
                self.log.traceback()
        elif self.inipickle:
            try:
                import obj2ini
                self.values = obj2ini.load(self.inipickle)
            except:
                self.log.traceback()
        easy = self.create_easy(mod, self.values)
        if easy.ShowModal() == wx.ID_OK:
            self.values = easy.GetValue()
            if self.picklefile:
                try:
                    import pickle
                    f = file(self.picklefile, 'wb')
                    pickle.dump(self.values, f)
                    f.close()
                except:
                    self.log.traceback()
            elif self.inipickle:
                try:
                    import obj2ini
                    obj2ini.dump(self.values, self.inipickle)
                except:
                    self.log.traceback()
                    
            if self.scriptfile:
                from meteor import TemplateScript, Template
                from StringIO import StringIO
                buf = StringIO()
                template = Template()
                template.load(self.scriptfile, 'text')
                buf.write(template.value('text', EasyUtils.str_object(self.values)))
                buf.seek(0)
                ts = TemplateScript()
                ts.run(buf, self.values)
                print buf.getvalue()
            elif self.templatefile:
                pass
            return True
        else:
            return False
        
    def create_easy(self, mod, values):
        if hasattr(mod, 'wizard'):
            import EasyWizard
            return EasyWizard.EasyWizard(None, bitmap=getattr(mod, 'bitmap', wx.NullBitmap), pagesinfo=mod.wizard, values=values)
        elif hasattr(mod, 'dialog'):
            import EasyDialog
            return EasyDialog.EasyDialog(None, title=getattr(mod, 'title', 'EasyDialog'), elements=mod.dialog, values=values)
        elif hasattr(mod, 'notebook'):
            import EasyNotebook
            return EasyNotebook.EasyNotebook(None, title=getattr(mod, 'title', 'EasyDialog'), pagesinfo=mod.notebook, values=values)
        
    def initlog(self):
        import logging
        self.log = log = logging.getLogger('EasyGUI')
        hdlr = logging.FileHandler('EasyAdmin.log')
        formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
        hdlr.setFormatter(formatter)
        log.addHandler(hdlr) 
        log.setLevel(logging.WARNING)
        
        def trace():
            message = traceback.format_exception(*sys.exc_info())
            log.error(''.join(message))
            
        log.traceback = trace
        
    def processCommandLineArguments(self):
        #process command line
        if self.inline:
            cmdstring = "t:s:p:w:i:"
        else:
            cmdstring = "vut:s:p:i:"
        try:
            opts, args = getopt.getopt(sys.argv[1:], cmdstring, [])
        except getopt.GetoptError:
            self.Usage()
            sys.exit(1)
         
        self.templatefile = ''
        self.scriptfile = ''
        self.picklefile = ''
        self.inipickle = ''
        for o, a in opts:
            if o == '-v':       #version
                self.Version()
                sys.exit()
            elif o == '-u':     #usage
                self.Usage()
                sys.exit()
            elif o == '-t':     #template
                self.templatefile = a
            elif o == '-s':     #template script
                self.scriptfile = a
            elif o == '-p':     #pickle
                self.picklefile = a
            elif o == '-e':
                self.wizardfile = a
            elif o == '-i':
                self.inipickle = a
            
        if not self.inline:
            try:
                self.wizardfile = args[0]
            except:
                self.Usage()
                sys.exit(1)
        
    def getPageModule(self):
        dirname = os.path.dirname(os.path.abspath(self.wizardfile))
        filename, ext = os.path.splitext(os.path.basename(self.wizardfile))
        if ext.lower() != '.py':
            return []
        if sys.modules.has_key(filename):
            del sys.modules[filename]
        if dirname:
            sys.path.insert(0, dirname)
        mod = __import__(filename)
        if dirname:
            del sys.path[0]
        return mod

    def GetValue(self):
        return self.values
        
    def Usage(self):
        print """Usage %s [options] EasyFilename
    
    -v      Show version
    -u      Show usage
    -t file Template file
    -s file Template script file
    -e file Easy Files (EasyWizard, EasyDialog, EasyNotebook)
    -p file Pickle file used to save input data
    -i file ini format Pickle file used to save input data
    
    If you want to use template function you should install Meteor package which can
    be found at http://wiki.woodpecker.org.cn/moin.cgi/Meteor. The Meteor version must
    be above 0.1.2 .
    """ % sys.argv[0]
    
    def Version(self):
        print """%s Copyleft GPL
Author: %s
Version: %s""" % (__appname__, __author__, __version__)


if __name__ == '__main__':
    easy = EasyCommander(False)
    easy.run()
    
