#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
# generated by wxGlade 0.4.1 on Sun Nov  5 21:18:09 2006

import wx, os.path, shutil, tempfile
import BIB

class Wizard_SQLite(wx.Panel):
    def __init__(self, *args, **kwds):
        # begin wxGlade: Wizard_SQLite.__init__
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)
        self.label_8 = wx.StaticText(self, -1, _("SQLite file"))
        self.label_1 = wx.StaticText(self, -1, _("Bibus uses a file to store the bibliographic database.\n\nPlease enter in the box below the path to \nthe bibliographic database you want to use.\n\n- If the file EXIST, Bibus will \n    - not modify it\n    - assume it to be a correct Bibus database.\n\n- If the file DOES NOT EXIST, Bibus will \n    - create it\n    - use it as your bibliographic database."))
        self.db_file = wx.Button(self, -1, _("Database file ..."))
        self.filen = wx.TextCtrl(self, -1, "")
        self.static_line_1 = wx.StaticLine(self, -1)
        self.label_9 = wx.StaticText(self, -1, _("Username"))
        self.label_2 = wx.StaticText(self, -1, _("Bibus needs a USERNAME to identify yourself.\nPlease enter a name in the box below.\nYour login name might be a good idea"))
        self.user = wx.TextCtrl(self, -1, "")

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.onFileChoice, self.db_file)
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: Wizard_SQLite.__set_properties
        self.label_8.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_9.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        # end wxGlade
        if BIB.SQLiteFile:
            self.filen.SetValue(BIB.SQLiteFile)
        else:
            f = tempfile.NamedTemporaryFile('w+b',-1,'.sqlite','DB_', os.path.join( wx.StandardPaths.Get().GetUserDataDir(), "Databases") )
            self.filen.SetValue(f.name)
            f.close()
        #
        if not BIB.CONFIG.userDefined('sqlite'):
            try:
                import getpass
                BIB.SQLiteUSER = getpass.getuser()    # We try to get a default value if not already defined.
            except:
                BIB.SQLiteUSER = ''
        self.user.SetValue(BIB.SQLiteUSER)

    def __do_layout(self):
        # begin wxGlade: Wizard_SQLite.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_1.Add(self.label_8, 0, wx.BOTTOM, 5)
        sizer_1.Add(self.label_1, 1, 0, 0)
        sizer_2.Add(self.db_file, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_2.Add(self.filen, 1, wx.ALL|wx.EXPAND, 0)
        sizer_1.Add(sizer_2, 0, wx.TOP|wx.EXPAND, 5)
        sizer_1.Add((20, 20), 0, 0, 0)
        sizer_1.Add(self.static_line_1, 0, wx.EXPAND, 0)
        sizer_1.Add(self.label_9, 0, wx.BOTTOM, 5)
        sizer_1.Add(self.label_2, 0, wx.EXPAND, 20)
        sizer_1.Add(self.user, 0, wx.TOP|wx.EXPAND, 5)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        # end wxGlade

    def onFileChoice(self,event): # wxGlade: Wizard_SQLite.<event_handler>
        if BIB.SQLiteFile:
            default = BIB.SQLiteFile
        else:
            default = 'biblioDB.sqlite'
        filename = wx.FileSelector(_('SQlite database file'),default_filename = default, flags = 2 ) # wx.FD_SAVE = 2 is missing in some version of wxPython
        self.filen.SetValue(filename)

    def createSQLiteDB(self):
        """create a sqlite database"""
        if not os.path.exists(BIB.SQLiteFile):
            shutil.copyfile( os.path.join(BIB.SOURCEDIR,'db_models','biblio.pysqlite2'), BIB.SQLiteFile )
        else:
            fileDB = open(BIB.SQLiteFile,'r')
            if fileDB.read(15) != 'SQLite format 3':
                wx.MessageBox(_("Your database has been created by an old sqlite version. You must convert to the new sqlite format as explained in http://bibus-biblio.sourceforge.net/wiki/index.php/Converting_a_SQLite_database"),_('Error'),wx.ICON_ERROR|wx.OK)
                return
            fileDB.close()
            self.convertDB()
            
    def getValues(self):
        return self.user.GetValue(),self.filen.GetValue()

    def convertDB(self):
        """ We convert SQLite db from bibus 1.3 or 1.4 to 1.5 by adding the table table_modif and/or table_file"""
        import dbBibSQLite
        #            
        db_old = dbBibSQLite.dbBib()
        db_old.selectTable()
        isDBok = True
        oldtables = db_old.getTables()
        for tab in (BIB.DB_TABLE_REF, BIB.DB_TABLE_KEY, BIB.DB_TABLE_LINK, BIB.DB_TABLE_QUERY, BIB.DB_TABLE_MODIF, BIB.DB_TABLE_FILE):
            if tab not in oldtables:
                isDBok = False
                break
        if isDBok: return    # All the tables are present, we can continue with the table
        
        # Otherwise we create a new clean db and we copy the data from the old to the new db
        # we create the database in the default location

        wx.MessageBox(_('Your database needs to be converted to the new format.\nThe original database file will not be changed, but a new copy will be created.\nThe conversion may take a while.'),_("Database conversion"),wx.OK)
        progress = wx.ProgressDialog(_("Database conversion"),\
            _("Conversion of your old SQLite database to the new bibus format. Please be patient."),\
            parent = self,
            style = wx.PD_AUTO_HIDE | wx.PD_APP_MODAL | wx.PD_SMOOTH | wx.PD_REMAINING_TIME )
            
        f = tempfile.NamedTemporaryFile('w+b',-1,'.sqlite','DB_', os.path.join( wx.StandardPaths.Get().GetUserDataDir(), "Databases") )
        BIB.SQLiteFile = f.name
        f.close()
        #
        db = dbBibSQLite.dbBib()
        db.createDatabase(BIB.SQLiteFile,BIB.DB_TABLE_REF,BIB.DB_TABLE_KEY,BIB.DB_TABLE_LINK,BIB.DB_TABLE_QUERY,BIB.DB_TABLE_MODIF,BIB.DB_TABLE_FILE)
        #
        refsId=[]
        tmprefs = db_old.getAllDatabase(collist=())
        refsId = [x[0] for x in tmprefs]
        progress.Update(10)
        # writing records
        if BIB.DB_TABLE_REF in oldtables:
            i = 0
            for refId in refsId:
                db.writeRef( db_old.getRef(refId,BIB.BIB_FIELDS)[0] )
                progress.Update(float(i)/len(refsId)*30+10)
                i+=1
        #progress.Update(25)
        # now we copy the keys
        if BIB.DB_TABLE_KEY in oldtables:
            for key in db_old.getAllKeys():
                db.dumpKey( key )
        progress.Update(40)
        # now the Links
        if BIB.DB_TABLE_LINK in oldtables:
            for link in db_old.getAllLinks():
                db.writeLink( link )
        progress.Update(55)
        # then the queries
        if BIB.DB_TABLE_QUERY in oldtables:
            for query in db_old.getAllQueries():
                db.dumpQuery( query )
        progress.Update(70)
        # now the modifs
        if BIB.DB_TABLE_MODIF in oldtables:
            for modif in db_old.getAllModifs():
                apply(db.resetCreator,modif)
        progress.Update(85)
        # and the files
        if BIB.DB_TABLE_FILE in oldtables:
            for filen in db_old.getAllFiles():
                db.setCreator( filen )
        progress.Update(100)
        progress.Destroy()
        # if default database is set in config DB_STARTUP=1, the new db won't be used at the next startup
        # we simply revert to the default setting, ie we open the last db.
        DB_STARTUP = 0
        #    
        wx.MessageBox(_('Your database has been converted to the new format.\nThe database is now located at\n"%s"')%f.name,_("Database conversion"),wx.OK)

# end of class Wizard_SQLite


