#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.9.5 on Thu Apr  2 08:19:01 2020
#
#----------------------------------------------------------------------------
# Name:         ldmStorageFolderViewFrm.py
# Purpose:      ldmStorageFolderViewFrm.py
#               GUI viewer for ldmStorageFolder
# Author:       Walter Obweger
#
# Created:      20200404
# CVS-ID:       $Id$
# Copyright:    (c) 2020 by Walter Obweger
# Licence:      MIT
#----------------------------------------------------------------------------


import wx
import wx.lib.gizmos as gizmos
import os
import logging
import traceback

# begin wxGlade: dependencies
# end wxGlade

# begin wxGlade: extracode
# end wxGlade

from lindworm import __version__
import lindworm.ldmGui as ldmGui
from lindworm.ldmArg import ldmArg
from lindworm.ldmWidApp import ldmWidApp
from lindworm.ldmWidFrmAui import ldmWidFrmAui
from lindworm.ldmGuiThd import ldmGuiThd
from lindworm.ldmWidThd import ldmWidThd
from lindworm.ldmWidPanel import ldmWidPanelFlxGrd
from lindworm.ldmStorageFolder import ldmStorageFolder

gOpt=None

class ldmStorageFolderViewFrm(ldmWidFrmAui):
    """storage folder view frame
    """
    WILDCARD_JSON=["json file (*.json)|*.json",
            "All files (*.*)|*.*"]
    def __initPanLf__(self,**kwargs):
        """initialize left pane

        Args:
            kwargs (dict): flexible keyword argument
        """
        try:
            # +++++ beg:initialize
            sOrg='ldmStorageFolderViewFrm::__initPanLf__'
            self.logDbg('beg:%s',sOrg)
            # ----- end:initialize
            # +++++ beg:
            # ----- end:
            # +++++ beg:finalize
            self.logDbg('end:%s',sOrg)
            # ----- end:finalize
        except:
            self.logTB()
    def __initPanCt__(self,**kwargs):
        """initialize center pane

        Args:
            kwargs (dict): flexible keyword argument
        """
        try:
            # +++++ beg:initialize
            sOrg='ldmStorageFolderViewFrm::__initPanLf__'
            self.logDbg('beg:%s',sOrg)
            # ----- end:initialize
            # +++++ beg:
            wNb=ldmWidFrmAui.__initPanCt__(self,**kwargs)
            self.widMainNB=wNb
            self.trlFdr = gizmos.TreeListCtrl(self.GetWid(), 
                                    wx.ID_ANY, 
                                    size=(400,300),
                                    style=0, 
                                    agwStyle=gizmos.TR_DEFAULT_STYLE|
                                    wx.TR_HIDE_ROOT|
                                    #| gizmos.TR_HAS_BUTTONS
                                    #| gizmos.TR_TWIST_BUTTONS
                                    #| gizmos.TR_ROW_LINES
                                    #| gizmos.TR_COLUMN_LINES
                                    #| gizmos.TR_NO_LINES
                                    #| gizmos.TR_LINES_AT_ROOT
                                    gizmos.TR_FULL_ROW_HIGHLIGHT
                                    )
            tSz = (16,16)
            il = wx.ImageList(*tSz)
            iIdxFdrCls  = il.Add(wx.ArtProvider.GetIcon(wx.ART_FOLDER,      wx.ART_OTHER, tSz))
            iIdxFdrOpn  = il.Add(wx.ArtProvider.GetIcon(wx.ART_FOLDER_OPEN, wx.ART_OTHER, tSz))
            iIdxFile    = il.Add(wx.ArtProvider.GetIcon(wx.ART_NORMAL_FILE, wx.ART_OTHER, tSz))
            self.dImgIdx={
                'FdrCls':iIdxFdrCls,
                'FdrOpn':iIdxFdrOpn,
                'File':iIdxFile,
                }
            self.trlFdr.SetImageList(il)
            self.trlFdr.AddColumn('name')
            self.trlFdr.AddColumn('size')
            self.trlFdr.AddColumn('time')
            self.trlFdr.AddColumn('sha')
            self.trlFdr.SetMainColumn(0)
            self.trlFdr.SetColumnWidth(0, 250)
            wNb.AddPage(self.trlFdr,'folder content',True)
            # ----- end:
            # +++++ beg:threading
            oWid=ldmWidThd(parent=wNb,iLv=0,
                        size=(200,120),sLogger='thdFdr',
                        )
            wNb.AddPage(oWid.GetWid(),'thd')
            self.wThd=oWid
            #self.wThd.SetFunc('start','launch',self.DoStart)
            # ----- end:threading
            # +++++ beg:
            iCol=3
            oWid=ldmWidPanelFlxGrd(parent=wNb,iLv=0,
                        size=(200,120),sLogger='pnDst',
                        iCol=iCol,lCol=[1],
                        lWid=[
                            ('lbl','lblDst01','destination 1'),
                            ('txt','txtDst01',''),
                            ('cbd','cdbDst01','txtDst01'),
                            ('lbl','lblDst02','destination 2'),
                            ('txt','txtDst02',''),
                            ('cbd','cdbDst02','txtDst02'),
                            ('lbl','lblDst03','destination 3'),
                            ('txt','txtDst03',''),
                            ('cbd','cdbDst03','txtDst03'),
                            ('lbl','lblDst04','destination 4'),
                            ('txt','txtDst04',''),
                            ('cbd','cdbDst04','txtDst04'),
                        ]
                        )
            wNb.AddPage(oWid.GetWid(),'destination')
            # ----- end:
            # +++++ beg:finalize
            self.logDbg('end:%s',sOrg)
            # ----- end:finalize
            return wNb
        except:
            self.logTB()
            return None
    def __initCfg__(self,**kwargs):
        """initialize configuration

        Args:
            kwargs (dict): flexible keyword argument
        """
        try:
            # +++++ beg:initialize
            sOrg='ldmWidFrmAui::__initCfg__'
            self.logDbg('beg:%s'%(sOrg))
            ldmWidFrmAui.__initCfg__(self,**kwargs)
            # ----- end:initialize
            # +++++ beg:
            self.CHC_DEF=["slot 00","slot 01","slot 02","slot 03"]
            # ----- end:
            # +++++ beg:finalize
            self.logDbg('end:%s'%(sOrg))
            # ----- end:finalize
        except:
            self.logTB()
    def __initDat__(self,**kwargs):
        """initialize data

        Args:
            kwargs (dict): flexible keyword argument
        """
        try:
            # +++++ beg:initialize
            sOrg='ldmStorageFolderViewFrm::__initDat__'
            self.logDbg('beg:%s',sOrg)
            # ----- end:initialize
            # +++++ beg:
            #self.sCfgFN=gOpt.sCfgFN      #"ldmStorageFolderCfg.json"
            #self.sBldFN=gOpt.sBldFN             #None
            #self.iVerbose=10
            # +++++ beg:
            self.oFdr=ldmStorageFolder(iVerbose=self.iVerbose)
            #iRet=oFdr.loadCfg(sCfgFN)
            # ----- end:
            # +++++ beg:finalize
            self.logDbg('end:%s',sOrg)
            # ----- end:finalize
        except:
            self.logTB()
    def __initPrp__(self,**kwargs):
        """initialize properties

        Args:
            kwargs (dict): flexible keyword argument
        """
        try:
            # +++++ beg:initialize
            sOrg='ldmStorageFolderViewFrm::__initPrp__'
            self.logDbg('beg:%s',sOrg)
            # ----- end:initialize
            # +++++ beg:
            sBldFN=self.pnCLI.txtBldFN.GetValue()
            self.logDbg('sBldFN:%s',sBldFN)
            iRet=self.shwFdr(sBldFN,sKey='0')
            if iRet>0:
                self.widMainNB.SetSelection(0)
            # ----- end:
            # +++++ beg:finalize
            self.logDbg('end:%s',sOrg)
            # ----- end:finalize
        except:
            self.logTB()

    def shwFdr(self,sFN,sKey='0'):
        """show folder

        Args:
            sFN (str): file name
            sKey (str , optional): source folder
            
        Returns:
            return code
                - >0 : okay processing done
                - =0 : okay nop
                - <0 : error
        """
        try:
            # +++++ beg:initialize
            sOrg='ldmStorageFolderViewFrm::shwFdr'
            self.logDbg('beg:%s sFN:%s sKey:%r',
                        sOrg,sFN,sKey)
            iRet=0
            self.trlFdr.DeleteAllItems()
            # ----- end:initialize
            # +++++ beg:
            iRet=self.oFdr.loadDat(sFN,sDN=None,
                            sKey=sKey,sAtr='dDat')
            itPar=self.trlFdr.AddRoot(sKey)
            if iRet>0:
                #dFdr=self.oFdr.dDat[sKey]
                iR,dFdr=self.oFdr.getDat(sKey)
                def getFmtSzHum(iSz):
                    fSz=iSz/1024/1024
                    return '%6.3f'%fSz
                def addElemFle(trlObj,itPar,dFdr):
                    iRet=0
                    iIdxFleOpn=self.dImgIdx['File']
                    iIdxFleCls=self.dImgIdx['File']
                    for sFdr,dSub in dFdr.items():
                        iRet+=1
                        itCur=trlObj.AppendItem(itPar, sFdr)
                        trlObj.SetItemImage(itCur, iIdxFleOpn, which = wx.TreeItemIcon_Normal)
                        #trlObj.SetItemImage(itCur, iIdxFdrCls , which = wx.TreeItemIcon_Expanded)
                        sSz=getFmtSzHum(dSub.get('sz',0))
                        trlObj.SetItemText(itCur,sSz, 1)
                        sTime=dSub.get('time','')
                        trlObj.SetItemText(itCur,sTime, 2)
                        sSha=dSub.get('sha','')
                        trlObj.SetItemText(itCur,sSha, 3)
                    return iRet
                def addElemFdr(trlObj,itPar,dFdr):
                    iRet=0
                    iIdxFdrOpn=self.dImgIdx['FdrOpn']
                    iIdxFdrCls=self.dImgIdx['FdrCls']
                    for sFdr,dSub in dFdr.items():
                        if sFdr=='.':
                            iRet+=1
                            itCur=trlObj.AppendItem(itPar, sFdr)
                            trlObj.SetItemImage(itCur, iIdxFdrOpn, which = wx.TreeItemIcon_Normal)
                            trlObj.SetItemImage(itCur, iIdxFdrCls , which = wx.TreeItemIcon_Expanded)
                            iR=addElemFle(trlObj,itCur,dSub)
                            if iR>0:
                                iRet+=1
                        else:
                            iRet+=1
                            itCur=trlObj.AppendItem(itPar, sFdr)
                            trlObj.SetItemImage(itCur, iIdxFdrOpn, which = wx.TreeItemIcon_Normal)
                            trlObj.SetItemImage(itCur, iIdxFdrCls , which = wx.TreeItemIcon_Expanded)
                            iR=addElemFdr(trlObj,itCur,dSub)
                            if iR>0:
                                iRet+=1
                    return iRet
                iR=addElemFdr(self.trlFdr,itPar,dFdr)
            # ----- end:initialize
            # +++++ beg:get DN
            self.logDbg('end:shwFdr iRet:%d sFN:%s',
                                iRet,sFN)
            # ----- end:get DN
            return iRet
        except:
            self.oFdr.logTB()
    def OnFileOpen(self,evt):
        """event callback open file

        Args:
            evt (obj): event object
        """
        try:
            self.logDbg('beg:OnFileOpen')
            # +++++ beg:get DN
            sBldFN='.'#self.txtBldFN.GetValue()
            # ----- end:get DN
            iRet,sBldFN=ldmGui.getFN(sBldFN,self.GetWid(),
                         'choose build file name',
                         lWildCard=self.WILDCARD_JSON,
                         oLog=self.oFdr)
            if iRet>0:
                iR=self.shwFdr(sBldFN,sKey='0')
                if iR>0:
                    iRet+=iR
                self.oFdr.log(0,'fin:OnBldFN iRet:%d sBldFN:%s',
                                iRet,sBldFN)
            self.logDbg('end:OnFileOpen')
        except:
            self.logTB()
    def OnCfgFN(self, event):  # wxGlade: ldmStorageFolderViewFrm.<event_handler>
        """event callback open configuration file

        Args:
            evt (obj): event object
        """
        event.Skip()
        try:
            sCfgFN=self.txtCfgFN.GetValue()
            iRet,sCfgFN=ldmGui.getFN(sCfgFN,self,
                         'choose configuration file name',
                         lWildCard=self.WILDCARD_JSON,
                         oLog=self.oFdr)
            if iRet>0:
                self.sCfgFN=sCfgFN
                self.txtCfgFN.SetValue(self.sCfgFN)
                self.oFdr.log(0,'fin:OnCfgFN iRet:%d sCfgFN:%s',
                            iRet,sCfgFN)
        except:
            self.oFdr.logTB()

def main(args=None):
    """main loop

    Args:
        args (list): command line arguments
    """
    # +++++ beg:
    # ----- end:
    
    # +++++ beg:init
    iRet=0
    iVerbose=5                                          # 20190624 wro:set default verbose level
    # ----- end:init
    # +++++ beg:define CLI arguments
    usage = "usage: %prog [options]"
    oArg=ldmArg(sUsage=usage,sVer=__version__,iVerbose=0)
    oArg.addOpt('sCfgFN',
            sDft='ldmStorageFolderViewCfg.json',
            sHlp='configuration file',
            sVerbose='config FN',
            sMeta='pyGatherMDCfg.json')
    oArg.addOpt('sBldFN',
            sDft='',
            sHlp='build directory',
            sVerbose='build FN',
            sMeta='path/to/output/folder')
    oArg.addOpt('sLogFN',
            sDft='./log/ldmStorageFolder.log',
            sHlp='log filename',
            sVerbose='log FN',
            sMeta='./log/ldmStorageFolder.log')

    # ----- end:define CLI arguments
    # +++++ beg:parse command line
    iRet=oArg.prcParse(args)
    # ----- end:parse command line
    # +++++ beg:prepare logging
    if oArg.sLogFN is not None:
        import lindworm.logUtil as logUtil
        logUtil.logInit(oArg.sLogFN,iLevel=logging.DEBUG)
    # ----- end:prepare logging
    # +++++ beg:
    app = ldmWidApp(0,
                title="lindworm storage folder viewer",
                oArg=oArg,
                clsFrm=ldmStorageFolderViewFrm)
    app.MainLoop()
    iRet+=1
    # ----- end:
    return iRet

if __name__ == "__main__":
    # +++++ beg:call entry point
    main(args=None)
    # ----- end:call entry point
