# 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.
#
import wx
import getpass, sys, os, imp
import BIB
from Pref_Display import Pref_Display
from Pref_Printing import Pref_Printing
from Pref_Search import Pref_Search
from Pref_Editor import Pref_Editor
from Pref_Shortcuts import Pref_Shortcuts
from Pref_Paths import Pref_Paths
from Pref_Duplicates import Pref_Duplicates
from Pref_DB import Pref_DB
from Pref_Connection import Pref_Connection
from Pref_PubMed import Pref_PubMed
from Pref_Journals import Pref_Journals
try:
    from FirstStart.OOoUNOconnection import getUNOconnection, setUNOconnection
except ImportError:
    pass

class BibPref(wx.Dialog):
    def __init__(self, db, *args, **kwds):
        self.db = db
        #kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Dialog.__init__(self, *args, **kwds)
        BIB.CONFIG.readConfig()    # we read the current config
        #
        s1 = wx.BoxSizer(wx.VERTICAL)    # top = checkpox Avanced ; medium = notebook ; bottom = buttons
        s2 = wx.BoxSizer(wx.HORIZONTAL)    # to put buttons in it
        s3 = wx.BoxSizer(wx.HORIZONTAL)    # Advanced pref on left ; elastic spacer ; buttons on right
        # buttons
        self.fullSetup = wx.CheckBox(self, -1, _("Advanced preferences"))
        self.button_ok = wx.Button(self, wx.ID_OK, _("OK"))
        self.button_cancel =wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        s2.Add(self.button_cancel,0,wx.ALL,5)
        s2.Add(self.button_ok,0,wx.ALL,5)
        self.button_ok.SetDefault()
        # notebook
        self.nb = wx.Notebook(self,-1,style=wx.NB_TOP)
        self.fullPrefs()
        # layout
        if wx.VERSION[:2] >= (2,6):    # wx.NotebookSizer no more needed with wx.Python2.6
            s1.Add(self.nb, 1, wx.EXPAND|wx.ALL,5)
        else:
            s1.Add(wx.NotebookSizer(self.nb), 1, wx.EXPAND|wx.ALL,5)
        s3.Add(self.fullSetup,0,wx.ALIGN_BOTTOM|wx.ALL,5)
        s3.Add((0,0),1)
        s3.Add(s2,0,wx.ALIGN_RIGHT)
        s1.Add(s3,0,wx.EXPAND)
        s1.Fit(self)
        self.SetSizer(s1)
        self.onAdvancedSetup(None)
        self.Layout()
        self.CenterOnParent()
        #
        self.__set_event()

    def __set_event(self):
        wx.EVT_BUTTON(self,wx.ID_OK,self.onOK)
        wx.EVT_BUTTON(self,wx.ID_CANCEL,self.onCloseWindow)
        wx.EVT_CLOSE(self, self.onCloseWindow)
        wx.EVT_CHECKBOX(self,self.fullSetup.GetId(),self.onAdvancedSetup)

    def onOK(self,event):
        # saving journal abbreviation settings
        tmpj = self.prefJournals.getSettings()
        if tmpj != BIB.JOURNAL:
            BIB.JOURNAL.clear()
            for line in tmpj.itervalues():
                BIB.JOURNAL[line[0].upper()] = line
                BIB.JOURNAL_ALTERNATE[line[0].upper()] = \
                BIB.JOURNAL_ALTERNATE[line[1].upper()] = \
                BIB.JOURNAL_ALTERNATE[line[2].upper()] = \
                line[0].upper()
            try: del BIB.JOURNAL_ALTERNATE[""]
            except KeyError: pass
            BIB.JOURNAL_MODIF = True
        # saving paths settings
        newpath = self.prefPaths.getSettings()
        if os.path.isdir(newpath):
            head, tail = os.path.split(newpath) # We need to remove trailing / from the path
            if tail:
                BIB.FILES = newpath
            else:
                BIB.FILES = head
        else:
            BIB.FILES = ""
        # saving Shortcuts settings
        BIB.SHORTCUTS, BIB.SHORT = self.prefShortcuts.getSettings()
        # 
        if self.fullSetup.GetValue():
            # getting display panel settings
            BIB.LIST_DISPLAY,BIB.KEY_COLOR,BIB.TEXT_COLOR = self.prefDisplay.getSettings()
            # we resize list_display
            if len(BIB.LIST_COL_SIZE) >= len(BIB.LIST_DISPLAY):
                BIB.LIST_COL_SIZE = BIB.LIST_COL_SIZE[:len(BIB.LIST_DISPLAY)]
            else:
                BIB.LIST_COL_SIZE = BIB.LIST_COL_SIZE + (BIB.LIST_COL_SIZE_DEFAULT,)*(len(BIB.LIST_DISPLAY) - len(BIB.LIST_COL_SIZE))
            self.GetParent().reflist.resizeList()
            if self.GetParent().keytree.GetSelection():
                self.GetParent().keytree.KeySelect(self.GetParent().keytree.GetSelection())
            # sort order
            #BIB.LIST_ORDER = self.sort_order.GetStringSelection()
            try:
                self.GetParent().resizeList()    # resize column list in reflist
                if self.GetParent().keytree.GetSelection():
                    self.GetParent().keytree.KeySelect(self.GetParent().keytree.GetSelection())
            except:
                pass
            #
            BIB.BIB_SEARCH_FIELDS = self.prefSearch.getSettings()
            #
            # we keep a copy of the current settings to know if we must re-connect onOK
            saved_db = BIB.DB_STARTUP,BIB.DB_TYPE,BIB.STORE_PASSWD,BIB.DB_NAME,BIB.USER,BIB.PASSWORD,BIB.HOST,BIB.PORT,BIB.SOCKET,BIB.SQLiteFile,BIB.SQLiteUSER
            BIB.DB_STARTUP,BIB.DB_TYPE,BIB.STORE_PASSWD,DB_NAME,USER,PASSWORD,HOST,PORT,SOCKET,SQLiteFile,SQLiteUSER = self.prefDB.getSettings()
            #
            if BIB.DB_STARTUP == 1:                    # db from default
                if BIB.DB_TYPE == 'MySQL':
                    BIB.DB_NAME = DB_NAME
                    BIB.USER = USER
                    if BIB.STORE_PASSWD:
                        BIB.PASSWORD = PASSWORD
                    else:
                        BIB.PASSWORD = ''
                    BIB.HOST = HOST
                    BIB.PORT = PORT
                    BIB.SOCKET = SOCKET
                elif BIB.DB_TYPE == 'SQLite':
                    BIB.SQLiteFile = SQLiteFile
                    BIB.SQLiteUSER = SQLiteUSER
            #
            # saving printing settings
            BIB.PRINTER_FORMAT, BIB.PRINTER_COLORS, BIB.PRINTER_STYLE, BIB.PRINTER_USE_OOo_FORMAT = self.prefPrinting.getSettings()
            # saving Reference editor settings
            BIB.EDIT = self.prefEditor.getSettings()
            # saving duplicates settings
            BIB.DUPLICATES_TEST, BIB.DUPLICATES, BIB.DUPLICATES_CASE, BIB.DUPLICATES_KEEP_OLD = self.prefDuplicates.getSettings()
            # saving wp connection settings
            (BIB.WP,),(BIB.OO_CON_TYPE,BIB.OO_PIPE,BIB.OO_HOST,BIB.OO_PORT),(BIB.LYX_PIPE,) = \
                                                                    self.prefConnection.getSettings()
            if BIB.WP == "OOo":
                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)
                    
            elif BIB.WP == "":
                try:
                    oldUNO = getUNOconnection()
                    newUNO = setUNOconnection( activate=False )
                except ImportError:
                    pass
            self.GetParent().switchConnectionMenu()            # we switch the menu from OOo/word/lyx/nothing if needed  
            #
            # loading dbBib module corresponding to the database type choice. if needed
            if saved_db != (BIB.DB_STARTUP,BIB.DB_TYPE,BIB.STORE_PASSWD,BIB.DB_NAME,BIB.USER,BIB.PASSWORD,BIB.HOST,BIB.PORT,BIB.SOCKET,BIB.SQLiteFile,BIB.SQLiteUSER):
                try:
                    f, pathname, description = imp.find_module('dbBib'+BIB.DB_TYPE)
                    BIB.DB_MODULE = imp.load_module('dbBib'+BIB.DB_TYPE, f, pathname, description)
                    #BIB.DB_MODULE = __import__('dbBib'+BIB.DB_TYPE)
                    #getattr(BIB.DB_MODULE,'dbBib')    # if the module was loaded before, re-importing won't raise ImportError. We must check directly if it works
                except ImportError:
                    BIB.DB_MODULE = None
                    wx.LogError(_("""Sorry, but I was not able to find the python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
                if f: f.close()
                self.GetParent().autoConnect()        # connect to the new database
                #
            # saving PubMed settings
            BIB.PUBMED,BIB.PUBMEDVIEW,BIB.PROXIES = self.Pref_PubMed.getSettings()
        #
        BIB.CONFIG.writeConfig(bool(BIB.DB_STARTUP))    # save the config changes with or without the database
        self.Close()

    def onCloseWindow(self,event):
        self.Destroy()

    def onAdvancedSetup(self,event):
        self.nb.Hide()
        self.nb.DeleteAllPages()
        if self.fullSetup.GetValue():
            self.fullPrefs()
        else:
            self.minPrefs()
        self.nb.Refresh()
        self.nb.Show()
        
    def fullPrefs(self):
        self.prefDisplay = Pref_Display(self.nb,-1, (BIB.LIST_DISPLAY,BIB.KEY_COLOR,BIB.TEXT_COLOR))
        self.prefPrinting = Pref_Printing(self.nb,-1)
        self.prefEditor = Pref_Editor(self.nb,-1)
        self.prefSearch = Pref_Search(self.nb,-1, BIB.BIB_SEARCH_FIELDS)
        self.prefDuplicates = Pref_Duplicates(self.nb,-1, (BIB.DUPLICATES_TEST,BIB.DUPLICATES,BIB.DUPLICATES_CASE,BIB.DUPLICATES_KEEP_OLD) )
        self.prefShortcuts = Pref_Shortcuts(self.db,self.nb,-1)
        self.prefPaths = Pref_Paths(self.nb,-1)
        self.prefDB = Pref_DB(self.nb,-1, (BIB.DB_STARTUP,BIB.DB_TYPE,BIB.STORE_PASSWD,BIB.DB_NAME,BIB.USER,BIB.PASSWORD,BIB.HOST,BIB.PORT,BIB.SOCKET,BIB.SQLiteFile,BIB.SQLiteUSER) )
        self.prefConnection = Pref_Connection(self.nb,-1,\
                        ((BIB.WP,),(BIB.OO_CON_TYPE,BIB.OO_PIPE,BIB.OO_HOST,BIB.OO_PORT),(BIB.LYX_PIPE,)))
        self.prefJournals = Pref_Journals(self.nb,-1, BIB.JOURNAL)
        self.Pref_PubMed = Pref_PubMed(self.nb,-1, (BIB.PUBMED,BIB.PUBMEDVIEW,BIB.PROXIES) )
        #
        self.nb.AddPage(self.prefDisplay,_("Display"))
        self.nb.AddPage(self.prefPrinting,_("Printing"))
        self.nb.AddPage(self.prefSearch,_("Search"))
        self.nb.AddPage(self.prefDuplicates,_("Duplicates"))
        self.nb.AddPage(self.prefEditor,_("Reference Editor"))
        self.nb.AddPage(self.prefJournals,_("Journals"))
        self.nb.AddPage(self.prefShortcuts,_("Shortcuts"))
        self.nb.AddPage(self.prefPaths,_("Paths"))
        self.nb.AddPage(self.prefDB,_("Database"))
        self.nb.AddPage(self.prefConnection,_("Word Processor"))
        self.nb.AddPage(self.Pref_PubMed,_("PubMed"))
        
    def minPrefs(self):
        self.prefJournals = Pref_Journals(self.nb,-1, BIB.JOURNAL)
        self.prefShortcuts = Pref_Shortcuts(self.db,self.nb,-1)
        self.prefPaths = Pref_Paths(self.nb,-1)
        self.nb.AddPage(self.prefJournals,_("Journals"))
        self.nb.AddPage(self.prefShortcuts,_("Shortcuts"))
        self.nb.AddPage(self.prefPaths,_("Paths"))
        
