#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##
##################################################
import os, sys, time
##################################################
import _rightThumb._construct as __
appDBA = __.clearFocus( __name__, __file__ )
__.appReg = appDBA
def focus( parentApp='', childApp='', reg=True ):
    global appDBA
    f = __.appName( appDBA, parentApp, childApp )
    if reg:
        __.appReg = f
    return f
__.registeredApps.append( focus() )
import _rightThumb._base3 as _
_.load()
##################################################
import _rightThumb._vars as _v
import _rightThumb._string as _str
##################################################

def appSwitches():
    _.switches.register( 'Files', '-f,-file,-files','file.txt', description='Files', isRequired=True )
    _.switches.register( 'Calendar', '-cal' )
    _.switches.register( 'Save', '-save' )
    pass
    ### EXAMPLE: START
    ### EXAMPLE: END

#   finds the file in probable locations
#   and 
#       if  _.autoBackupData = True
#       and __.releaseAcquiredData = True
#           GET EPOCH FROM: hosts/hostname/logs/apps/execution_receipt-app_name-epoch.json
#       you can run apps on usb at a clients office
#           when you get home run: p app -loadepoch epoch 
#               backed up
#                   pipe
#                   files
#                   tables
_.autoBackupData = __.setting('receipt-log')
__.releaseAcquiredData = __.setting('receipt-file')
__.myFileLocations_SKIP_VALIDATION = False
__.isRequired_Pipe = False
__.isRequired_Pipe_or_File = False
__.pre_error = False
__.switch_raw = []
# __.switch_raw = [ 'Delim' ]
# __.isRequired_or_List = ['Pipe','Files','Plus']
# __.setting( 'app-switches-raw', [ 'Delim' ] )


_.appInfo[focus()] = {
    'file': 'vps-hoth-7i0ZA-7GzGHN-client-cleanup.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'Clean clients json fields',
    'categories': [
                        'data',
                        'field',
                        'clean',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('b lo'),
                        _.hp('p vps-hoth-7i0ZA-7GzGHN-client-cleanup -f clients.json'),
                        _.hp('p vps-hoth-7i0ZA-7GzGHN-client-cleanup -f clients.json -cal calendar.json'),
                        '',
    ],
    'columns': [
                       # { 'name': 'name', 'abbreviation': 'n' },
                       # { 'name': '{1}', 'abbreviation': '{0}', 'sort': '{2}' },
    ],
    'aliases': [
                       # 'this',
                       # 'app',
    ],
    'notes': [
                       # {},
    ],
}

_.appData[focus()] = {
        'start': __.startTime,
        'uuid': '',
        'audit': [],
        'pipe': False,
        'data': {
                    'field': {'sent': [], 'received': [] }, # { 'label': '', 'context': [],  }
                    'table': {'sent': [], 'received': [] }, 
        },
    }



def registerSwitches( argvProcessForce=False ):
    global appDBA
    if not __.appReg == appDBA and appDBA in __.appReg:

        if not __name__ == '__main__':
            _.argvProcess = argvProcessForce
        else:
            _.argvProcess = True

        _.load()
        _.appInfo[__.appReg] = _.appInfo[appDBA]
        _.appData[__.appReg] = _.appData[appDBA]
    __.constructRegistration( _.appInfo[__.appReg]['file'],__.appReg )
    appSwitches()

    _.myFileLocation_Print = False
    # _.switches.trigger( 'Files', _.myFileLocations, vs=True )
    _.switches.trigger( 'Folder', _.myFolderLocations )
    _.switches.trigger( 'URL', _.urlTrigger )
    _.switches.trigger( 'Ago', _.timeAgo )
    _.switches.trigger( 'Duration', _.timeFuture )
    ### EXAMPLE: START
    # _.default_switch_trigger('Plus', trigger_plus)
    # _.switches.trigger( 'Files',_.inRelevantFolder )  
    # _.switches.trigger( 'Watched', _.txt2Date )
    # _.switches.trigger( 'Input',_.formatColumns )
    # _.switches.trigger( 'Franchise',_.triggerSpace )
    ### EXAMPLE: END
    
    _.defaultScriptTriggers()
    _.switches.process()


if not __name__ == '__main__':
    _.argvProcess = False
else:
    _.argvProcess = True

registerSwitches()


def fieldSet( switchName, switchField, switchValue, theFocus=False ):
    if not type( theFocus ) == bool:
        theFocus = theFocus
    _.switches.fieldSet( switchName, switchField, switchValue, theFocus )


if __name__ == '__main__':
    if not sys.stdin.isatty():
        _.setPipeData( sys.stdin.readlines(), __.appReg, clean=True )


_.postLoad( __file__ )

########################################################################################
#   if os.path.isdir( row ):
#   if os.path.isfile( row ):
#   os.path.abspath(path)
#                                                   if platform.system() == 'Windows':
########################################################################################
# START



def action():
    load()
    global data
    index={}
    omit = []
    for i,rec in enumerate( data ):
        data[i]['i'] = i
        data[i] = _clean.imp.app.record.process(rec)
        if rec['Id'] in [
                            '7ebcdea8-05e3-4a6e-84c1-5bba01ac11f8',
                            '3bc840f9-7e4f-4c8f-a20b-7b885d6559e1',
                            '9f87dd22-d1b3-4100-a966-40c46c185951',
                        ]:
            omit.append( i )
        else:
            for k in 'Email Phone Mobile'.split(' '):
                scan=_clean.imp.app.scan.process( data[i][k], 'A02F28B2' )
                if 'phone' in scan:
                    for da in scan['phone']:
                        index[da]=i
                if 'email' in scan:
                    for da in scan['email']:
                        if not da in 'claytonfrank@hotmail.com'.split(' '):
                           index[da.lower()]=i

    pass
    if not _.switches.isActive('Calendar') and _.switches.isActive('Save'):
        _.saveTable2( data, _.switches.values('Save')[0] )
        return None
        # _.pr()
        # _.pr()
        # for k in 'BillingName ContactName BillingAddress ShippingAddress Email Phone Mobile Website Notes'.split(' '):

        # _.pr()
        # _.pr()        # for k in 'Phone Mobile'.split(' '):
        #     if rec[k]:
        #         _.pr(k,data[i][k])
    pass
    if _.switches.isActive('Calendar'):
        thresh = _.timeAgo( '+10y', time.time() )
        threshB = _.timeAgo( '-1y', time.time() )
        # _.pr( _.friendlyDate(thresh) )
        cal_client_ids = []
        cal_client_ids_index = {}
        index_subject = {}
        cal = _.getTable2(_.switches.values('Calendar')[0])
        pass
        m=0
        


        for ii,rec in enumerate(cal):
            isService = False
            for k in rec:
                if type(rec[k]) == str:
                    if 'service' in rec[k]:
                        isService = True
            # if isService:
            if 1:
                for k in rec:
                    scan=_clean.imp.app.scan.process( rec[k], 'A02F28B2' )
                    matches = []
                    if 'phone' in scan:
                        for da in scan['phone']:
                            da = _clean.imp.app.phone.process( da )
                            if da in index:
                                if not index[da] in omit:
                                    _.pr(da)
                                    # _.pr(1)
                                    matches.append(index[da])
                    if 'email' in scan:
                        for da in scan['email']:
                            da=da.lower()
                            if da in index:
                                if not index[da] in omit:
                                    _.pr(da)
                                    # _.pr(1)
                                    matches.append(index[da])
                    if len(matches):
                        m+=1
                    for i in matches:
                        epoch =  _.autoDate( rec['dtstart'] )
                        # if epoch > threshB:
                        if epoch > time.time():
                            if not i in cal_client_ids_index:
                                index_subject[i] = rec['summary']
                                cal_client_ids_index[i] = epoch
                            elif epoch < cal_client_ids_index[i]:
                                index_subject[i] = rec['summary']
                                cal_client_ids_index[i] = epoch
                            cal_client_ids.append({'cal':ii,'client':i,'epoch': epoch })
                        # _.pr(i, data[i]['BillingName'])
        pass
        _.pr('_____________')
        if _.switches.isActive('Save'):
            newDex = {}
            labels = {}
            for i in cal_client_ids_index:
                labels[ data[i]['Id'] ] = index_subject[i]
                newDex[ data[i]['Id'] ] = cal_client_ids_index[i]

            _.saveTable2( newDex, _.switches.values('Save')[0] )
            _.saveTable2( labels, 'labels-'+_.switches.values('Save')[0] )

        return cal_client_ids
        # _.pr()
        # _.pr()
        # _.pr('',m,'cal matches of',len(cal))

    return data

                


def load():
    global data
    global cities
    data = _.getTable2( _.switches.values('Files')[0] )


    

_clean = _.regImp( __.appReg, 'record-cleaner' )
# _copy = _.regImp( __.appReg, '-copy' )
# sys.exit()
# _copy.imp.copy(  )
# focus()
# _clean.imp.app.record.process(  )



########################################################################################
if __name__ == '__main__':
    action()
    __.isExit()





