# Copyright 2004,2005 Pierre Martineau <pmartino@users.sourceforge.net>
# This file is part of Bibus, a bibliographic database that can
# work together with OpenOffice.org to generate bibliographic indexes.
#
# Bibus 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.
#
# Bibus 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 Bibus; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
#
# Part of the Wizard code has been copied from the example "Simple Wizard" included with
# wx.Python
#
import getpass, os, sys, ConfigParser, cPickle, csv
#
import wx, wx.wizard
import BIB
#from FirstTimeWizard_WP import FirstTimeWizard_WP
from FirstTimeWizard_DB import DB_Engine
from Wizard_MySQL import Wizard_MySQL, Wizard_MySQL_choiceDB
from Wizard_SQLite import Wizard_SQLite
from Pref_Connection import Pref_Connection
try:
    from OOoUNOconnection import getUNOconnection, setUNOconnection
except ImportError:
    pass

# ----------------------------------------------------------------
class TitledPage(wx.wizard.WizardPageSimple):
    def __init__(self, parent, title):
        wx.wizard.WizardPageSimple.__init__(self, parent)
        self.sizer = self.__makePageTitle(title)

    def __makePageTitle(self, title):
        sizer = wx.BoxSizer(wx.VERTICAL)
        title = wx.StaticText(self, -1, title)
        title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))
        sizer.Add(title, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
        sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.ALL, 5)
        self.SetSizer(sizer)
        return sizer
        
# ----------------------------------------------------------------
class FirstStart(wx.wizard.Wizard):
    """This is the Frame that open on the firstconnection"""
    def __init__(self,parent):
    # Create the wizard and the pages
        self.sqliteversion='2'        # version of sqlite used (depend on the pysqlite module)
        self.ID_wiz = wx.NewId()
        self.parent = parent
        cp = ConfigParser.ConfigParser()
        #
        wx.wizard.Wizard.__init__(self,parent, self.ID_wiz, _("First Connection Wizard"),bitmap = wx.Bitmap(os.path.join(BIB.SOURCEDIR,"Pixmaps","bibusWizard.png")))
        self.Show(1)
        self.pageWP = TitledPage(self,  _("Welcome to Bibus !"))
        # self.pageOOo = TitledPage(self, _("OpenOffice.org connection"))
        self.pageDB = TitledPage(self, _("Database engine"))
        self.pageSQLite = TitledPage(self, _("SQLite setup"))
        self.pageMySQL = TitledPage(self, _("MySQL setup"))
        self.pageMySQLdb = TitledPage(self, _("MySQL database"))
        #
        # pageWP Layout. Choice of MS Word or OOo connection
        # self.panel_wp = FirstTimeWizard_WP(self.pageWP,-1,wizard = self)
        self.panel_wp = Pref_Connection(self.pageWP,-1,\
            ((BIB.WP,),(BIB.OO_CON_TYPE,BIB.OO_PIPE,BIB.OO_HOST,BIB.OO_PORT),(BIB.LYX_PIPE,)))
        self.pageWP.sizer.Add( self.panel_wp, 1, wx.EXPAND )
        # pageDB = DB choice layout
        self.pageDB.sizer.Add( DB_Engine(self.pageDB, -1), 1, wx.EXPAND)
        # pageSQLite
        self.panel_sqlite = Wizard_SQLite(self.pageSQLite, -1)
        self.pageSQLite.sizer.Add( self.panel_sqlite, 1, wx.EXPAND)
        # pageMySQL 1
        self.panel_mysql = Wizard_MySQL(self.pageMySQL, -1)
        self.pageMySQL.sizer.Add( self.panel_mysql, 1, wx.EXPAND)
        # pageMySQL 2
        self.panel_mysqldb = Wizard_MySQL_choiceDB(self.pageMySQLdb, -1)
        self.pageMySQLdb.sizer.Add( self.panel_mysqldb, 1, wx.EXPAND)
        # Chaining the pages
        wx.wizard.WizardPageSimple_Chain(self.pageWP, self.pageDB)
        #
        self.chainDB()
        self.Layout()
        #
        wx.wizard.EVT_WIZARD_PAGE_CHANGED(self, self.ID_wiz, self.OnWizPageChanged)
        wx.wizard.EVT_WIZARD_PAGE_CHANGING(self, self.ID_wiz, self.OnWizPageChanging)
        wx.wizard.EVT_WIZARD_CANCEL(self, self.ID_wiz, self.OnWizCancel)
        wx.wizard.EVT_WIZARD_FINISHED(self, self.ID_wiz, self.OnWizFinish)
        
    def chainDB(self):
        """Chaining the correct page depending on the DB choice"""
        if BIB.DB_TYPE == "MySQL":
            wx.wizard.WizardPageSimple_Chain(self.pageDB, self.pageMySQL)
            wx.wizard.WizardPageSimple_Chain(self.pageMySQL,self.pageMySQLdb)
        else:
            wx.wizard.WizardPageSimple_Chain(self.pageDB, self.pageSQLite)

    def Run(self):
        self.FitToPage(self.pageWP)
        self.RunWizard(self.pageWP)

    def OnWizPageChanged(self, evt):
        page = evt.GetPage()
        if page == self.pageSQLite:
            #self.panel_sqlite.check()    # we check pysqlite or sqlite exist
            return                        # not needed anymore since we use python >= 2.5 which includes sqlite3 module
        elif page == self.pageMySQL:
            self.panel_mysql.check()    # we check MySQLdb exists
        elif page == self.pageMySQLdb:
            BIB.USER,BIB.PASSWORD,BIB.HOST,BIB.PORT,BIB.SOCKET = self.panel_mysql.getValues()
            self.panel_mysqldb.setDB()
            
    def OnWizPageChanging(self, evt):
        page = evt.GetPage()
        if page == self.pageWP:
            (BIB.WP,),(BIB.OO_CON_TYPE,BIB.OO_PIPE,BIB.OO_HOST,BIB.OO_PORT),(BIB.LYX_PIPE,) = \
                                                                              self.panel_wp.getSettings()
            if BIB.WP == "OOo":
                try:
                    oldUNO = getUNOconnection()
                    if BIB.OO_CON_TYPE == 1:
                        newUNO = setUNOconnection( linktype='pipe', parameters=(BIB.OO_PIPE,), activate=True)
                    elif BIB.OO_CON_TYPE == 0:
                        newUNO = setUNOconnection( linktype='socket', parameters=(BIB.OO_HOST,str(BIB.OO_PORT)), activate=True)
                    if newUNO != oldUNO:
                        wx.MessageBox( _("OpenOffice.org settings have changed. You must close and restart OpenOffice.org before being able to use the connection."),_("Information"),style = wx.ICON_INFORMATION | wx.OK)
                except NameError:
                    wx.MessageBox( _("An error occured during OpenOffice.org connection setup. Re-install OpenOffice.org and try again"),_("Information"),style = wx.ICON_INFORMATION | wx.OK)
                    
            elif BIB.WP == "":
                try:
                    oldUNO = getUNOconnection()
                    newUNO = setUNOconnection( activate=False )
                except NameError:
                    pass

    def convertJournals(self):
        """Convert Journal abbreviations from format in bibus1.4 to the new
        csv format in bibus1.5"""
        oldlocaljpath = os.path.join(wx.StandardPaths.Get().GetUserDataDir(),'Data','journals')
        newlocaljpath = os.path.join(wx.StandardPaths.Get().GetUserDataDir(),'Data',BIB.JOURNAL_FILE)
        if os.path.exists(oldlocaljpath) and not os.path.exists(newlocaljpath):
            old = cPickle.load( file(oldlocaljpath) )
            new = file(newlocaljpath, "w" )
            output = csv.writer(new)
            output.writerows( old.itervalues() )
            new.close()

    def OnWizFinish(self, evt):
        # we are leaving the wizard by clicking the Finish button
        # we get the values from the different panels
        # then we exit
        if BIB.DB_TYPE == 'SQLite':
            BIB.SQLiteUSER, BIB.SQLiteFile = self.panel_sqlite.getValues()
            self.panel_sqlite.createSQLiteDB()
        else:
            BIB.USER,BIB.PASSWORD,BIB.HOST,BIB.PORT,BIB.SOCKET = self.panel_mysql.getValues()
            BIB.DB_NAME = self.panel_mysqldb.getValues()
        #
        self.NoFirstStart()
        BIB.CONFIG.writeConfig(not bool(BIB.DB_STARTUP))
        self.convertJournals()

    def OnWizCancel(self, evt):
        return

    def NoFirstStart(self):
        BIB.FIRST_START = False
        BIB.CONFIG.firstStartDone()

