#!/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( 'Latitude', '-lat,-latitude' )
    _.switches.register( 'Longitude', '-lon,-longitude' )
    _.switches.register( 'Epoch-Index', '-dex' )
    _.switches.register( 'Ago', '-ago' )
    _.switches.register( 'JSON', '-json' )
    _.switches.register( 'Test', '-test' )
    _.switches.register( 'Labels', '-labels' )
    pass

_.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-coordinates-distance.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'closest clients to gps location',
    'categories': [
                        'client',
                        'gps',
                        'distance',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p thisApp -file file.txt'),
                        '',
    ],
    '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 )
    
    _.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__ )

########################################################################################
# START
latitude=float(_.switches.values('Latitude')[0])
longitude=float(_.switches.values('Longitude')[0])
def calc(lat,lon):
    global latitude
    global longitude
    # approximate radius of earth in km
    R = 6373.0

    lat1 = radians(latitude)
    lon1 = radians(longitude)
    lat2 = radians(lat)
    lon2 = radians(lon)

    dlon = lon2 - lon1
    dlat = lat2 - lat1

    a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))

    distance = R * c
    return round(distance*0.621371,1)
    # _.pr("distance:", distance)
    # _.pr("Should be:", 278.546, "km")

def process(rec):
    dis = round(rec['distance'],3)
    _.pr( '<hr/>', dis, 'miles' )
    _.pr( rec['BillingName'] )
    if len(rec['Mobile']):
        _.pr( rec['Mobile'] )
    elif len(rec['Phone']):
        _.pr( rec['Phone'] )
    if len(rec['BillingAddress']):
        _.pr( rec['BillingAddress'] )
    elif len(rec['ShippingAddress']):
        _.pr( rec['ShippingAddress'] )
    # _.pr('<hr/>')

def simpy(rec):
    scanned={}
    for k in rec:
        scan=_clean.imp.app.scan.process( rec[k] )
        # if scan:
            # _.pr(scan)
        for f in scan:
            if not f in scanned:
                scanned[f]=[]
            for g in scan[f]:
                scanned[f].append(g)
    # if scanned:
    #     _.pr(scanned)
    phone=[]
    email=[]
    if 'phone' in scanned:
        for da in scanned['phone']:
            phone.append(da)
    if 'email' in scanned:
        for da in scanned['email']:
            email.append(da)
    # if email:
    #     _.pr(email)

    simp = {}
    simp['i'] = rec['i']
    simp['Id'] = rec['Id']
    simp['miles'] = rec['miles']
    simp['BillingName'] = rec['BillingName']
    simp['Mobile'] = _clean.imp.app.phone.process(rec['Mobile'])
    simp['Phone'] = _clean.imp.app.phone.process(rec['Phone'])
    simp['phones'] = ', '.join(phone)
    simp['Email'] = ', '.join(email)
    simp['BillingAddress'] = _clean.imp.app.address.process(rec['BillingAddress'])
    simp['ShippingAddress'] = _clean.imp.app.address.process(rec['ShippingAddress'])
    simp['NextService'] = rec['NextService']
    simp['Scheduled'] = rec['Scheduled']
    simp['ServiceLabel'] = rec['ServiceLabel']
    for k in simp:
        if type(simp[k]) == str:
            simp[k] = _str.do('dup',simp[k],' ')
            simp[k] = _str.do('be',simp[k],' ')
    
    simp['BillingAddress'] = simp['BillingAddress'].replace('united','United')
    simp['BillingAddress'] = simp['BillingAddress'].replace('states','States')
    simp['BillingAddress'] = simp['BillingAddress'].replace('ameriaca','America')
    simp['BillingAddress'] = simp['BillingAddress'].replace('United States of America','')
    simp['BillingAddress'] = simp['BillingAddress'].replace('United States','')
    simp['BillingAddress'] = _str.do('be',simp['BillingAddress'],' ')

    simp['ShippingAddress'] = simp['ShippingAddress'].replace('united','United')
    simp['ShippingAddress'] = simp['ShippingAddress'].replace('states','States')
    simp['ShippingAddress'] = simp['ShippingAddress'].replace('ameriaca','America')
    simp['ShippingAddress'] = simp['ShippingAddress'].replace('United States of America','')
    simp['ShippingAddress'] = simp['ShippingAddress'].replace('United States','')
    simp['ShippingAddress'] = _str.do('be',simp['ShippingAddress'],' ')
    


    temp=''
    for t in simp['BillingName']:
        if t in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@ '+"'":
            temp+=t

    # for t in simp['phones']:
    #     if t in '0123456789':
    #         temp+=t
    #     else:
    #         temp+=' '
    temp = _str.do('dup',temp,' ')
    temp = _str.do('be',temp,' ')
    temp2=[]
    for rt in temp.split(' '):
        if not '@' in rt:
            temp2.append(rt)
    simp['BillingName']=' '.join(temp2)

    # simp['Scheduled-Date'] = rec['Scheduled-Date']
    return simp



def int_epoch(epoch):
    e = str(epoch).split('.')[0]
    return int(e)

def action():
    # should be   Single-Task   OR   Imply-Architecture-Functions   OR   CLASSES!!
    load()
    global data
    global iclient

    index = {}
    labels = {}
    if _.switches.isActive('Labels'):
        labels = _.getTable2( _.switches.values('Labels')[0] )
    if _.switches.isActive('Epoch-Index'):
        index = _.getTable2( _.switches.values('Epoch-Index')[0] )
    # _.pv(index)
    records=[]
    scheduled = []
    # _.pv(index)
    # sys.exit()
    for i,rec in enumerate( data ):
        ID = str(rec['Id'])
        if ID in index:
            # _.pr('found')
            # sys.exit()
            if ID in labels:
                data[i]['ServiceLabel'] = labels[ID]
            else:
                data[i]['ServiceLabel'] = ''
            data[i]['Scheduled'] = index[ID]
            data[i]['NextService'] = _.friendlyDate( index[ID] ).split(' ')[0]
            data[i]['Scheduled-Date'] = data[i]['NextService']
            if _.switches.isActive('Test'):
                _.pr( data[i]['Scheduled'], data[i]['NextService'], data[i]['BillingName'] )
            
            # _.pr(index[ID])
        else:
            data[i]['ServiceLabel'] = ''
            data[i]['NextService'] = ''
            data[i]['Scheduled-Date'] = ''
            data[i]['Scheduled'] = 0

        
        if 'latitude' in  rec['coordinates']:
            data[i]['distance']=calc(rec['coordinates']['latitude'],rec['coordinates']['longitude'])
            data[i]['miles']=round(rec['distance'],3)
            if data[i]['Scheduled']:
                scheduled.append(rec['i'])
            
            records.append(data[i])




    
    ago = time.time() + ( 86400*30 )
    # _.pv( _.isDate(ago) )
    # sys.exit()
    if _.switches.isActive('Ago'):
        ago = _.switches.value('Ago')
    # _.pr( ago )
    # _.pv( _.isDate(ago) )
    # sys.exit()


    IDS = []
    order = []
    cnt=0
    newData = _.tables.returnSorted( 'data', 'a.distance', records )
    simple = []
    spent = []

    for i, rec in enumerate(newData):
        ID = rec['Id']
        order.append(ID)
        if cnt < 11:
            if index and ID in index and index[ID] > time.time() and index[ID] < ago:
                IDS.append(i)
                cnt+=1
                if not ID in spent:
                    spent.append(ID)
                    simple.append(simpy(rec))
                
                if not _.switches.isActive('JSON'):
                    process(rec)

            else:
                cnt+=1
                if not ID in spent:
                    spent.append(ID)
                    simple.append(simpy(rec))
                if not _.switches.isActive('JSON'):
                    process(rec)
    pass
    if  _.switches.isActive('JSON'):

        # for i in scheduled:
        #   rec=data[i]
        #   if not i in spent:
        #       spent.append(i)
        #       simple.append(simpy(rec))

        for i in order:
            rec=iclient[i]
            if not i in spent:
                spent.append(i)
                simple.append(simpy(rec))


    elif not _.switches.isActive('JSON'):
        if cnt < 11:
            for i in order:
                if cnt < 11:
                    if not i in IDS:
                        cnt+=1
                        process(newData[i])
                    



    # _.pr('<hr/>')


    for i, rec in enumerate(simple):
        simple[i]['rank'] = i+1


    dic = {}
    dic['now'] = int_epoch(time.time())
    dic['ago'] = int_epoch(ago)
    dic['epochs'] = index
    dic['clients'] = simple
    if not _.switches.isActive('Test'): 
        if _.switches.isActive('JSON'):
            _.pv(dic)
            sys.exit()


def load():
    global data
    global iclient
    data = _.getTable2( _.switches.values('Files')[0] )
    fo='/home/admin/domains/eyeformeta.com/private_html/apps/clients/7i0ZA/gps/data/records'
    try:
        if os.path.isdir(fo):
            for fi in _.fo(fo):
                # path=fo+os.sep+fi
                # path=fo+os.sep+fi
                data.append( _.getTable2(fi) )
    except Exception as e:
        pass
    iclient = {}
    for rec in data:
        iclient[ rec['Id'] ] = rec

from math import sin, cos, sqrt, atan2, radians
_clean = _.regImp( __.appReg, 'record-cleaner' )


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





