#!/usr/bin/env python
#-*- coding: UTF-8 -*-
 
import wx
from stomamisc import *


class PrefsDialog(wx.Dialog):
    """ all settings for this app """
    ID_BTN_COLOUR = wx.NewId()
    ID_CTRL_DB3 = wx.NewId()
    ID_RADIOBOX = wx.NewId()
    ID_RADIOBUTTON1 = wx.NewId()
    ID_RADIOBUTTON2 = wx.NewId()
    ID_RADIOORDER = wx.NewId()
    ID_RADIOUNITS = wx.NewId()
    ID_CB_GRID = wx.NewId()
    ID_CB_CONFIRM = wx.NewId()
    ID_CB_CASE = wx.NewId()
    ID_CB_AUTOEX = wx.NewId()
    ID_CB_UPDATE = wx.NewId()
    ID_CB_PRIORITY = wx.NewId()
    ID_CB_HIDDEN = wx.NewId()
    ID_CB_ERRORLOG = wx.NewId()
    ID_CB_ACTIONLOG = wx.NewId()
    ID_CB_MINI = wx.NewId()
    ID_CB_AUTODB = wx.NewId()
    

    def __init__(self, parent, color, inifilename):
        """ place preferences items on a dialog with 4 tabs """
        wx.Dialog.__init__(self, parent, -1, TITLE + ' - Preferences')
        self.config = parent.config
        self.color = color
        background_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BACKGROUND)
        self.Centre()
        sizer = wx.BoxSizer(wx.VERTICAL)
        row1 = wx.BoxSizer(wx.HORIZONTAL)
        self.nb = wx.Notebook(self, -1)
        row1.Add(self.nb) #, 1, wx.GROW | wx.ALL, GAP)        

        self.initTab1()
        self.initTab2()
        self.initTab3(background_color)
        self.initTab4(inifilename, background_color)
        
        butok = wx.Button(self, wx.ID_OK, '&OK')
        self.Bind(wx.EVT_BUTTON, self.onOk, id = wx.ID_OK)
        butcancel = wx.Button(self, wx.ID_CANCEL, '&Cancel')
        
        row2 = wx.BoxSizer(wx.HORIZONTAL)
        row2.AddStretchSpacer()
        row2.Add(butok, 0, wx.GROW | wx.ALL, BORDER)
        row2.Add(butcancel, 0, wx.GROW | wx.ALL, BORDER)
        row2.AddStretchSpacer()

        sizer.Add(row1, 0, wx.GROW | LRT, BORDER)
        sizer.Add(row2, 0, wx.GROW | wx.LEFT | wx.RIGHT, BORDER)
        self.SetSizer(sizer)
        self.Fit()
        self.Center()
    #-------------------------------------------------------------------------------------------

    def initTab1(self):
        page1 = wx.Panel(self.nb, -1)
        p1sizer = wx.BoxSizer(wx.VERTICAL)
        exsz = wx.FlexGridSizer(3, 2, 0, 0)
        exsz.AddGrowableCol(1)
        st = wx.StaticText(page1, -1, 'Start minimized:')
        exsz.Add(st, 0, wx.ALL, GAP)
        self.cbm = wx.CheckBox(page1, self.ID_CB_MINI, ' (if checked - icon in systray)') 
        exsz.Add(self.cbm, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckMini, id = self.ID_CB_MINI)
        self.cbm.SetValue(self.config['Execution']['startmin'] == 'True')
        st = wx.StaticText(page1, -1, 'Scheduled job start:')
        exsz.Add(st, 0, wx.ALL, GAP)
        self.cbx = wx.CheckBox(page1, self.ID_CB_AUTOEX, ' (if checked - execute enabled jobs)') 
        exsz.Add(self.cbx, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckAutoExec, id = self.ID_CB_AUTOEX)
        self.cbx.SetValue(self.config['Execution']['autoexec'] == 'True')
        st = wx.StaticText(page1, -1, 'Scheduler offset (sec):')
        exsz.Add(st, 0, wx.ALL, GAP)
        self.sc = wx.SpinCtrl(page1, -1)
        self.sc.SetRange(0, 600)            # max 10 minutes
        self.sc.SetValue(int(self.config['Execution']['offset']))
        self.Bind(wx.EVT_SPINCTRL, self.onOffset)
        exsz.Add(self.sc, 0, wx.GROW | wx.ALL, GAP)
                                                  
        p1sizer.Add(exsz, 0, wx.GROW | LRT, BORDER)
        page1.SetSizer(p1sizer)
        self.nb.AddPage(page1, ' Execution ')       
    #-------------------------------------------------------------------------------------------

    def initTab2(self):
        page2 = wx.Panel(self.nb, -1)
        p2sizer = wx.BoxSizer(wx.VERTICAL)  
        lcsz = wx.FlexGridSizer(6, 2, 0, 0)
        lcsz.AddGrowableCol(1)
        st = wx.StaticText(page2, -1, 'with Grid:     ')
        lcsz.Add(st, 0, wx.ALL, GAP)
        self.cbg = wx.CheckBox(page2, self.ID_CB_GRID, ' (change applied after program restart)') 
        lcsz.Add(self.cbg, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckGrid, id = self.ID_CB_GRID)
        self.cbg.SetValue(self.config['ListCtrl']['grid'] == 'True')        
        enu = wx.FontEnumerator()
        enu.EnumerateFacenames()
        fontlist = enu.GetFacenames()
        fontlist.sort()
        st = wx.StaticText(page2, -1, 'Font family:    ')
        lcsz.Add(st, 0, wx.ALL, GAP)
        cbfont = wx.ComboBox(page2, -1, self.config['ListCtrl']['font'], 
                             choices = fontlist, style = wx.CB_DROPDOWN | wx.CB_READONLY)
        lcsz.Add(cbfont, 0, wx.GROW | wx.ALL, GAP)
        self.Bind(wx.EVT_COMBOBOX, self.onFontComboBox, cbfont)
        try:
            cbfont.SetSelection(fontlist.index(self.config['ListCtrl']['font']))
        except:
            pass
       
        st = wx.StaticText(page2, -1, 'Font size:')
        lcsz.Add(st, 0, wx.ALL, GAP)
        scfsize = wx.SpinCtrl(page2, -1)
        scfsize.SetRange(6, 16)           
        scfsize.SetValue(int(self.config['ListCtrl']['fsize']))
        lcsz.Add(scfsize, 0, wx.GROW | wx.ALL, GAP)
        self.Bind(wx.EVT_SPINCTRL, self.onFontSize, scfsize)
        
        st = wx.StaticText(page2, -1, '')
        lcsz.Add(st, 0, wx.GROW | wx.ALL, GAP)
        msgtext = wx.StaticText(page2, -1, 'Example: name_of_filemanager [options] %dir')
        font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
        msgtext.SetFont(font)
        lcsz.Add(msgtext, 0, wx.GROW | wx.ALL, GAP)
        
        st = wx.StaticText(page2, -1, 'Filemanager:')
        lcsz.Add(st, 0, wx.ALL, GAP)
        self.cbfileman = wx.ComboBox(page2, -1, self.config['ListCtrl']['fileman'][0], 
                                     choices = self.config['ListCtrl']['fileman'],
                                     style = wx.TE_PROCESS_ENTER)
        lcsz.Add(self.cbfileman, 0, wx.GROW | wx.ALL, GAP)
        self.Bind(wx.EVT_TEXT_ENTER, self.onFilemanComboBox, self.cbfileman)

        st = wx.StaticText(page2, -1, 'Confirmation:')
        lcsz.Add(st, 0, wx.ALL, GAP)
        self.cbc = wx.CheckBox(page2, self.ID_CB_CONFIRM, ' (if checked - show remove item dialog)') 
        lcsz.Add(self.cbc, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckConfirm, id = self.ID_CB_CONFIRM)
        self.cbc.SetValue(self.config['ListCtrl']['confirm'] == 'True')        
                
        p2sizer.Add(lcsz, 0, wx.GROW | LRT, BORDER)        
        page2.SetSizer(p2sizer)
        self.nb.AddPage(page2, ' ListControl ')
    #-------------------------------------------------------------------------------------------

    def initTab3(self, background_color):
        page3 = wx.Panel(self.nb, -1)
        p3sizer = wx.BoxSizer(wx.VERTICAL)         
        dbsz = wx.FlexGridSizer(5, 2, 0, 0)
        dbsz.AddGrowableCol(1)
               
        st = wx.StaticText(page3, -1, 'Auto update:')
        dbsz.Add(st, 0, wx.ALL, GAP)
        self.cbau = wx.CheckBox(page3, self.ID_CB_AUTODB, ' (if checked - job exec updates db)') 
        dbsz.Add(self.cbau, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckAutoUpd, id = self.ID_CB_AUTODB)
        self.cbau.SetValue(self.config['Database']['autoupd'] == 'True')
        st = wx.StaticText(page3, -1, 'Ignore case:')
        dbsz.Add(st, 0, wx.ALL, GAP)
        self.cbi = wx.CheckBox(page3, self.ID_CB_CASE, ' (only in queries)') 
        dbsz.Add(self.cbi, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckCase, id = self.ID_CB_CASE)
        self.cbi.SetValue(self.config['Database']['ignorecase'] == 'True')

        self.unitlist = ['B', 'KB', 'MB']
        st = wx.StaticText(page3, -1, 'Query filter: ')
        dbsz.Add(st, 0, wx.ALL | wx.ALIGN_TOP, GAP)
        rb = wx.RadioBox(page3, self.ID_RADIOUNITS, ' Filesize units ', wx.DefaultPosition, wx.DefaultSize,
                         ['Bytes', 'Kilo-Bytes', 'Mega-Bytes'], 1, wx.RA_SPECIFY_COLS) # | wx.NO_BORDER)
        dbsz.Add(rb, 0, wx.ALL | wx.GROW, GAP)        
        self.Bind(wx.EVT_RADIOBOX, self.onRadioUnit, id = self.ID_RADIOUNITS)
        rb.SetSelection(self.unitlist.index(self.config['Misc']['unit']))

        self.orderlist = ['dirname', 'filename', 'filedate']
        st = wx.StaticText(page3, -1, 'Query result:')
        dbsz.Add(st, 0, wx.ALL | wx.ALIGN_TOP, GAP)
        rbob = wx.RadioBox(page3, self.ID_RADIOORDER, ' Default order by ', wx.DefaultPosition, wx.DefaultSize,
                           self.orderlist, 1, wx.RA_SPECIFY_COLS) # | wx.NO_BORDER)
        self.Bind(wx.EVT_RADIOBOX, self.onRadioOrder, id = self.ID_RADIOORDER)
        rbob.SetSelection(self.orderlist.index(self.config['Database']['orderby']))
        dbsz.Add(rbob, 0, wx.GROW | wx.LEFT | wx.RIGHT, GAP)
        
        st = wx.StaticText(page3, -1, 'Display limit:')
        dbsz.Add(st, 0, wx.ALL, GAP)
        self.tclimit = wx.lib.intctrl.IntCtrl(page3, value = int(self.config['Database']['limit']), 
                                              style = wx.TE_PROCESS_ENTER)
        dbsz.Add(self.tclimit, 0, wx.GROW | wx.ALL, GAP)
        st = wx.StaticText(page3, -1, 'Current path:  ')
        dbsz.Add(st, 0, wx.ALL, GAP)
        self.ctrldb = wx.TextCtrl(page3, self.ID_CTRL_DB3,
                                  self.config['Database']['dbhistory'][int(self.config['Database']['index'])],
                                  style = wx.TE_READONLY)
        self.ctrldb.SetBackgroundColour(background_color)
        dbsz.Add(self.ctrldb, 0, wx.GROW | wx.ALL, GAP)                

        p3sizer.Add(dbsz, 0, wx.GROW | LRT, BORDER)                
        page3.SetSizer(p3sizer)
        self.nb.AddPage(page3, ' Database ')
    #-------------------------------------------------------------------------------------------

    def initTab4(self, inifilename, background_color):
        page4 = wx.Panel(self.nb, -1)
        p4sizer = wx.BoxSizer(wx.VERTICAL)  
        miscsz = wx.FlexGridSizer(7, 2, 0, 0)
        miscsz.AddGrowableCol(1)
        st = wx.StaticText(page4, -1, 'Update check:')
        miscsz.Add(st, 0, wx.ALL, GAP)
        self.cbup = wx.CheckBox(page4, self.ID_CB_UPDATE, ' (if checked - auto examine website)')
        miscsz.Add(self.cbup, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckUpdate, id = self.ID_CB_UPDATE)
        self.cbup.SetValue(self.config['Misc']['update'] == 'True')        
        st = wx.StaticText(page4, -1, 'Priority:')
        miscsz.Add(st, 0, wx.ALL, GAP)
        self.cbp = wx.CheckBox(page4, self.ID_CB_PRIORITY, ' (if checked - scan / backup priority reduced)')
        miscsz.Add(self.cbp, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckPriority, id = self.ID_CB_PRIORITY)
        self.cbp.SetValue(self.config['Misc']['priority'] == 'True')        
        st = wx.StaticText(page4, -1, 'Hidden dirs:')
        miscsz.Add(st, 0, wx.ALL, GAP)
        self.cbh = wx.CheckBox(page4, self.ID_CB_HIDDEN, ' (if checked - show hidden dirs in dialogs)')
        miscsz.Add(self.cbh, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckHidden, id = self.ID_CB_HIDDEN)
        self.cbh.SetValue(self.config['Misc']['hiddendirs'] == 'True')        
        st = wx.StaticText(page4, -1, 'Backup log:')
        miscsz.Add(st, 0, wx.ALL, GAP)
        self.cbe = wx.CheckBox(page4, self.ID_CB_ERRORLOG, ' (if checked - write skip / error infos to logfile)')
        miscsz.Add(self.cbe, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckErrorlog, id = self.ID_CB_ERRORLOG)
        self.cbe.SetValue(self.config['Misc']['errorlog'] == 'True')
        st = wx.StaticText(page4, -1, 'Action log:')
        miscsz.Add(st, 0, wx.ALL, GAP)
        self.cba = wx.CheckBox(page4, self.ID_CB_ACTIONLOG, ' (if checked - write Log messages to logfile)')
        miscsz.Add(self.cba, 0, wx.ALL, GAP)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckActionlog, id = self.ID_CB_ACTIONLOG)
        self.cba.SetValue(self.config['Misc']['actionlog'] == 'True')        
        st = wx.StaticText(page4, -1, 'Highlight colour:')
        miscsz.Add(st, 0, wx.ALL, GAP)
        colsizer = wx.BoxSizer(wx.HORIZONTAL)  
        butcolour = wx.Button(page4, self.ID_BTN_COLOUR, ' Select new colour ')
        self.Bind(wx.EVT_BUTTON, self.onColour, id = self.ID_BTN_COLOUR)
        colsizer.Add(butcolour, 0, wx.ALL, GAP)
        self.tccolor = wx.TextCtrl(page4, -1, ' %s ' % (str(self.color)), size = wx.Size(130, -1), style = wx.TE_READONLY)
        self.tccolor.SetBackgroundColour(self.color)
        colsizer.Add(self.tccolor, 0, wx.ALL | wx.GROW, GAP)
        miscsz.Add(colsizer, 0, wx.GROW, GAP)
        st = wx.StaticText(page4, -1, 'Ini path:')
        miscsz.Add(st, 0, wx.ALL, GAP)
        self.ctrlini = wx.TextCtrl(page4, -1, inifilename, style = wx.TE_READONLY)
        self.ctrlini.SetBackgroundColour(background_color)
        miscsz.Add(self.ctrlini, 0, wx.ALL | wx.GROW, GAP)
        st = wx.StaticText(page4, -1, 'CSV path:')
        miscsz.Add(st, 0, wx.ALL, GAP)
        self.ctrlcsv = wx.TextCtrl(page4, self.ID_CTRL_DB3, self.config['Misc']['csvname'],
                                   style = wx.TE_READONLY)
        self.ctrlcsv.SetBackgroundColour(background_color)        
        miscsz.Add(self.ctrlcsv, 0, wx.ALL | wx.GROW, GAP)

        p4sizer.Add(miscsz, 0, wx.GROW | LRT, BORDER)        
        page4.SetSizer(p4sizer)
        self.nb.AddPage(page4, ' Misc ')
    #-------------------------------------------------------------------------------------------

    def onColour(self, event):
        data = wx.ColourData()
        data.SetColour(self.color)
        dlg = wx.ColourDialog(self, data)
        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetColourData()
            self.color = data.GetColour().Get()
            self.tccolor.SetValue(' %s ' % (str(self.color)))
            self.tccolor.SetBackgroundColour(self.color)
    #-------------------------------------------------------------------------------------------

    def onFontComboBox(self, event):
        self.config['ListCtrl']['font'] = event.GetString()
    #-------------------------------------------------------------------------------------------

    def onFontSize(self, event):        
        self.config['ListCtrl']['fsize'] = str(event.GetInt())
    #-------------------------------------------------------------------------------------------

    def onFilemanComboBox(self, event = None):
        txtitem = self.cbfileman.GetValue()
        if not txtitem:
            txtitem = self.config['ListCtrl']['fileman'][0]
            self.cbfileman.SetValue(txtitem)
            
        if txtitem != self.config['ListCtrl']['fileman'][0]:
            if txtitem in self.config['ListCtrl']['fileman']:
                self.config['ListCtrl']['fileman'].remove(txtitem)
            self.config['ListCtrl']['fileman'].insert(0, txtitem)
            if len(self.config['ListCtrl']['fileman']) == 9:
                del self.config['ListCtrl']['fileman'][8]
            self.cbfileman.Clear()
            for item in self.config['ListCtrl']['fileman']:
                self.cbfileman.Append(item)
            self.cbfileman.SetValue(txtitem)
    #-------------------------------------------------------------------------------------------

    def onCheckConfirm(self, event):
        self.config['ListCtrl']['confirm'] = event.GetString()
    #-------------------------------------------------------------------------------------------

    def onRadioDb(self, event):
        """  """
        if event.Id == self.ID_RADIOBUTTON1:
            append = 'True'
        else:
            append = 'False'
        self.config['Database']['append'] = append 
    #-------------------------------------------------------------------------------------------
 
    def onOk(self, event):
        self.onFilemanComboBox()
        event.Skip()
    #-------------------------------------------------------------------------------------------
 
    def onOffset(self, event):
        self.config['Execution']['offset'] = str(event.GetInt())
    #-------------------------------------------------------------------------------------------
    
    def onCheckMini(self, event):
        self.config['Execution']['startmin'] = str(self.cbm.GetValue())
    #-------------------------------------------------------------------------------------------

    def onCheckCase(self, event):
        """  """
        self.config['Database']['ignorecase'] = str(self.cbi.GetValue())
    #-------------------------------------------------------------------------------------------

    def onRadioOrder(self, event):
        """  """
        orderby = self.orderlist[event.GetInt()]
        self.config['Database']['orderby'] = orderby 
    #-------------------------------------------------------------------------------------------

    def onCheckAutoUpd(self, event):
        """  """        
        if self.cbau.GetValue():
            self.config['Database']['autoupd'] = 'True'
        else:
            msg = 'Unchecking this box is not recommended (except in special cases)! If yo do so, backup information will not be written automatically to the database and the database will get out of sync.\nDo you realy want to uncheck?'
            dlg = wx.MessageDialog(self, msg, TITLE + ' - Auto update',  wx.NO  | wx.NO_DEFAULT  | wx.YES | wx.ICON_WARNING)
            if dlg.ShowModal() == wx.ID_YES:
                self.config['Database']['autoupd'] = 'False'        
        self.cbau.SetValue(self.config['Database']['autoupd'] == 'True')
    #-------------------------------------------------------------------------------------------

    def onRadioUnit(self, event):
        """  """
        unit = self.unitlist[event.GetInt()]
        self.config['Misc']['unit'] = unit 
    #-------------------------------------------------------------------------------------------

    def onCheckGrid(self, event):
        """  """
        self.config['ListCtrl']['grid'] = str(self.cbg.GetValue())
    #-------------------------------------------------------------------------------------------

    def onCheckAutoExec(self, event):
        self.config['Execution']['autoexec'] = str(self.cbx.GetValue())
    #-------------------------------------------------------------------------------------------

    def onCheckUpdate(self, event):
        """  """
        self.config['Misc']['update'] = str(self.cbup.GetValue())
    #-------------------------------------------------------------------------------------------

    def onCheckPriority(self, event):
        """  """
        self.config['Misc']['priority'] = str(self.cbp.GetValue())
    #-------------------------------------------------------------------------------------------

    def onCheckHidden(self, event):
        """  """
        self.config['Misc']['hiddendirs'] = str(self.cbh.GetValue())
    #-------------------------------------------------------------------------------------------

    def onCheckErrorlog(self, event):
        """  """
        self.config['Misc']['errorlog'] = str(self.cbe.GetValue())
    #-------------------------------------------------------------------------------------------

    def onCheckActionlog(self, event):
        """  """
        self.config['Misc']['actionlog'] = str(self.cba.GetValue())
    #-------------------------------------------------------------------------------------------

    def getNewConfig(self):
        """  """
        self.config['Database']['limit'] = self.tclimit.GetValue()
        self.config['Misc']['hlcolor'] = self.color
        return self.config
# - class PrefDialog(wx.Dialog):----------------------------------------------------------------

