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


class ManageScanDirsDialog(wx.Dialog):
    
    ID_HIST = wx.NewId()
    ID_CHECK = wx.NewId()
    ID_SCAN = wx.NewId()
    ID_CB_HIDDEN = wx.NewId()
    
    def __init__(self, parent, updateScanList, writeToLogwin, config):        
        """ Manage (add, remove) scan dirs dialog """
        wx.Dialog.__init__(self, parent, -1, TITLE + ' - Manage scan dirs',                           
                           style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)                             
        self.Bind(wx.EVT_CLOSE, self.onButtonClose)
        self.Bind(wx.EVT_RIGHT_DOWN, self.onContext)        
        self.config = config
        self.hidden = config['Misc']['hiddendirs'] == 'True'
        self.parent = parent
        lasttarget = config['Scan']['lasttarget']
        if not os.path.exists(lasttarget):
            lasttarget = os.sep
        self.doubleclicked = False   # workaround
        self.updateScanList = updateScanList
        self.writeToLogwin = writeToLogwin
        sizer = wx.BoxSizer(wx.VERTICAL)
        gbsz = wx.GridBagSizer(BORDER, BORDER)      
        
        sb = wx.StaticBox(self, -1, ' Select scandir to add ')
        col1 = wx.StaticBoxSizer(sb, wx.VERTICAL)
        self.dirctrl = wx.GenericDirCtrl(self,  style = wx.DIRCTRL_DIR_ONLY | wx.SUNKEN_BORDER)
        col1.Add(self.dirctrl, 2, wx.GROW | wx.ALL, GAP)
        self.dirctrl.ShowHidden(self.hidden)
        style = self.dirctrl.GetTreeCtrl().GetWindowStyle() | wx.TR_FULL_ROW_HIGHLIGHT
        self.dirctrl.GetTreeCtrl().SetWindowStyle(style)
        self.dirctrl.SetPath(lasttarget)
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.onSelChange)
        #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.onTreeDclicked)
        self.dirctrl.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.onContext)        
                
        self.st = wx.TextCtrl(self, -1, lasttarget, style = wx.TE_READONLY)
        self.st.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BACKGROUND))
        col1.Add(self.st, 0, wx.GROW | wx.ALL, GAP)
        
        self.cbh = wx.CheckBox(self, self.ID_CB_HIDDEN, ' show hidden / dotted dirs')
        self.cbh.SetValue(self.hidden)
        self.Bind(wx.EVT_CHECKBOX, self.onCheckHidden, id = self.ID_CB_HIDDEN)      
        col1.Add(self.cbh, 0, wx.LEFT | wx.RIGHT, GAP)        
        gbsz.Add(col1, wx.GBPosition(0, 0), wx.GBSpan(2, 1), wx.GROW)
        
        sb = wx.StaticBox(self, -1, ' Scandir history ')
        col2 = wx.StaticBoxSizer(sb, wx.VERTICAL)
        self.lb = wx.ListBox(self, self.ID_HIST, choices = config['Scan']['history'],
                             size = wx.Size(190, -1), style = wx.LB_SINGLE | wx.LB_HSCROLL)
        col2.Add(self.lb, 1, wx.GROW | wx.ALL, GAP)
        self.Bind(wx.EVT_LISTBOX, self.onListBoxClicked, id = self.ID_HIST)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.onListBoxDClicked, id = self.ID_HIST)
        self.lb.Bind(wx.EVT_RIGHT_DOWN, self.onContext)
        gbsz.Add(col2, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.GROW)        

        sb = wx.StaticBox(self, -1, ' Currently select scandirs ')
        row3 = wx.StaticBoxSizer(sb, wx.VERTICAL)
        self.clb = wx.ListBox(self, self.ID_CHECK, choices = config['Scan']['scandirs'],
                                   size = wx.Size(190, -1), style = wx.LB_SINGLE | wx.LB_HSCROLL)
        self.clb.Bind(wx.EVT_RIGHT_DOWN, self.onContext)
        row3.Add(self.clb, 1, wx.GROW | wx.ALL, GAP)
        gbsz.Add(row3, wx.GBPosition(1, 1), wx.GBSpan(1, 1), wx.GROW)
        
        butadd = wx.Button(self, wx.ID_ADD)
        butrem = wx.Button(self, wx.ID_REMOVE)
        butclear = wx.Button(self, wx.ID_CLEAR)
        butclose = wx.Button(self, wx.ID_CLOSE)
        self.Bind(wx.EVT_BUTTON, self.onButtonClose, id = wx.ID_CLOSE)
        self.Bind(wx.EVT_BUTTON, self.onButtonAdd, id = wx.ID_ADD)
        self.Bind(wx.EVT_BUTTON, self.onButtonRem, id = wx.ID_REMOVE)
        self.Bind(wx.EVT_BUTTON, self.onButtonClear, id = wx.ID_CLEAR)
        row4 = wx.BoxSizer(wx.HORIZONTAL)
        row4.Add(butadd, 1, wx.GROW | wx.RIGHT, GAP)
        row4.Add(butrem, 1, wx.GROW | wx.LEFT | wx.RIGHT, GAP)
        row4.Add(butclear, 1, wx.GROW | wx.LEFT | wx.RIGHT, GAP)
        row4.Add(butclose, 1, wx.GROW | wx.LEFT, GAP)
        gbsz.Add(row4, wx.GBPosition(2, 0), wx.GBSpan(1, 2), wx.GROW)
        
        gbsz.AddGrowableRow(0)
        gbsz.AddGrowableRow(1)        
        gbsz.AddGrowableCol(0)
        gbsz.AddGrowableCol(1)
        
        sizer.Add(gbsz, 1, wx.GROW | wx.ALL, BORDER)
        self.SetSizer(sizer)
        self.SetMinSize(wx.Size(640, 480))
        self.Fit()
        self.Centre()
        self.initContextMenu()
    #-------------------------------------------------------------------------------------------

    def initContextMenu(self):
        self.popupID0 = wx.NewId()  
        self.popupID1 = wx.NewId()          
        self.popupID2 = wx.NewId()
        self.popupID3 = wx.NewId()
        
        self.Bind(wx.EVT_MENU, self.onButtonAdd, id = self.popupID0)
        self.Bind(wx.EVT_MENU, self.onButtonRem, id = self.popupID1)
        self.Bind(wx.EVT_MENU, self.onButtonClear, id = self.popupID2)
        self.Bind(wx.EVT_MENU, self.onButtonClose, id = self.popupID3)
    #-------------------------------------------------------------------------------------------

    def onContext(self, event):
        """ context menu handler """
        menu = wx.Menu()
        menu.Append(self.popupID0, 'Add scandir')
        menu.Append(self.popupID1, 'Remove scandir(s)')
        menu.Append(self.popupID2, 'Clear scandirs')
        menu.AppendSeparator()
        menu.Append(self.popupID3, 'Close dialog')
        self.PopupMenu(menu)
        menu.Destroy()
    #-------------------------------------------------------------------------------------------

    def onCheckHidden(self, event):
        self.hidden = not self.hidden
        self.dirctrl.ShowHidden(self.hidden)        
    #-------------------------------------------------------------------------------------------

    def onListBoxClicked(self, event):
        if self.doubleclicked:
            self.doubleclicked = False  # workaround
        else:
            path = self.config['Scan']['history'][event.GetInt()]
            if os.path.exists(path):
                self.dirctrl.SetPath(path)
            else:
                dlg = wx.MessageDialog(self, "The selected scandir\n'%s'\nis currently not available" % \
                                                               (path), TITLE + ' - Manage scan dirs',
                                                               wx.OK | wx.ICON_WARNING)
                dlg.ShowModal()
    #-------------------------------------------------------------------------------------------

    def onTreeDclicked(self, event):
        if LINUX:
            self.onButtonAdd()
        else:
            event.Skip()
    #-------------------------------------------------------------------------------------------
        
    def onListBoxDClicked(self, event):
        self.doubleclicked = True
        self.onButtonAdd(None, self.config['Scan']['history'][event.GetInt()])
    #-------------------------------------------------------------------------------------------
        
    def onButtonAdd(self, event = None, path = ''):
        if len(path) == 0:
            path = self.dirctrl.GetPath()
        self.config['Scan']['scandirs'].append(path)
        self.clb.Clear()
        self.clb.InsertItems(self.config['Scan']['scandirs'], 0)
        self.writeToLogwin("Manage scan - scan directory '%s' added to list" % (path))
        
        if path in self.config['Scan']['history']:
            self.config['Scan']['history'].remove(path)
            
        self.config['Scan']['history'].insert(0, path)
        if len(self.config['Scan']['history']) == 8:
            del self.config['Scan']['history'][7]
        
        self.lb.Set(self.config['Scan']['history'])
        self.updateScanList()
        self.Layout()
    #-------------------------------------------------------------------------------------------

    def onButtonRem(self, event):
        scanids = self.clb.GetSelections()
        if len(scanids):
            scandir = self.config['Scan']['scandirs'][scanids[0]]
            del self.config['Scan']['scandirs'][scanids[0]]
            self.writeToLogwin("Manage scan - scan dir '%s' removed from list" % (scandir))
        else:
            self.writeToLogwin('Manage scan - no scan dir removed from list')
        self.clb.Set(self.config['Scan']['scandirs'])        
        self.updateScanList()
        self.Layout()
    #-------------------------------------------------------------------------------------------

    def onButtonClear(self, event):
        self.config['Scan']['scandirs'] = []
        self.clb.Set(self.config['Scan']['scandirs'])  
        self.updateScanList()
        self.Layout()
    #-------------------------------------------------------------------------------------------

    def onButtonClose(self, event):
        self.Destroy()
    #-------------------------------------------------------------------------------------------

    def onSelChange(self, event):
        seldir = self.dirctrl.GetPath()
        self.st.SetValue(seldir)
        self.config['Scan']['lasttarget'] = seldir
        self.Layout()
# - class AddScanDirDialog(wx.Dialog):---------------------------------------------------------------

