#!/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( 'Delete', '-delete' )
    pass
    ### EXAMPLE: START
    # _.switches.register( 'Files', '-f,-file,-files','file.txt', isData='glob,name,data,clean', description='Files', isRequired=True )
    ### 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-srv-7facG-twilio-retrieve.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'Changes the world',
    'categories': [
                        'DEFAULT',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p vps-srv-7facG-twilio-retrieve'),
                        '',
    ],
    '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
v = _.dot()
def default(arg):
    return arg
v.script=default
def trigger(s):
    v.script=s
def action():

    # Download the helper library from https://www.twilio.com/docs/python/install
    import os
    from twilio.rest import Client


    # Find your Account SID and Auth Token at twilio.com/console
    # and set the environment variables. See http://twil.io/secure
    # account_sid = os.environ['TWILIO_ACCOUNT_SID']
    # auth_token = os.environ['TWILIO_AUTH_TOKEN']
    account_sid = _keychain.imp.key('twillio-account-sid')
    auth_token = _keychain.imp.key('twillio-auth-token')
    
    client = Client(account_sid, auth_token)

    messages = client.messages.list(limit=20)
    # _.pr(messages)
    for record in messages:
        # _.pr()
        # _.pr()
        rec = {
                    'sid': record.sid,
                    'to': record.to,
                    'from': record.from_,
                    'body': record.body,
                    'media': record.body,
                    'uri': record.uri,
        }
        v.script(rec)
        # _.pr(record.body)
        # _.pr(record.body)
        # for x in dir(record):
        #     if not x.startswith('_'):
        #         _.pr(x)
        # sys.exit()
        if '7755356008' in record.to:
            _.pv(rec)
        if not record.body:
            # _.pv(rec)
            for x in dir(record):
                try:
                    _.pr(x, eval('record.'+x))
                except Exception as e:
                    pass
        if _.switches.isActive('Delete'):
            ask=input('Delete Y/n: ')
            if not 'n' in ask:
                client.messages(record.sid).delete()
        # for x in dir(record):
        #   _.pr(x)
        # _.pr(record)


    '''
    account_sid
    api_version
    body
    date_created
    date_sent
    date_updated
    delete
    direction
    error_code
    error_message
    feedback
    fetch
    from_
    media
    messaging_service_sid
    num_media
    num_segments
    price
    price_unit
    sid
    status
    subresource_uris
    to
    update
    uri
    '''

    # EXAMPLE JSON RESPONSE
    # {
    #   "end": 1,
    #   "first_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2008-01-02&PageSize=2&Page=0",
    #   "next_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2008-01-02&PageSize=2&Page=1&PageToken=PAMMc26223853f8c46b4ab7dfaa6abba0a26",
    #   "page": 0,
    #   "page_size": 2,
    #   "previous_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2008-01-02&PageSize=2&Page=0",
    #   "messages": [
    #     {
    #       "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    #       "api_version": "2010-04-01",
    #       "body": "testing",
    #       "date_created": "Fri, 24 May 2019 17:44:46 +0000",
    #       "date_sent": "Fri, 24 May 2019 17:44:50 +0000",
    #       "date_updated": "Fri, 24 May 2019 17:44:50 +0000",
    #       "direction": "outbound-api",
    #       "error_code": null,
    #       "error_message": null,
    #       "from": "+12019235161",
    #       "messaging_service_sid": null,
    #       "num_media": "0",
    #       "num_segments": "1",
    #       "price": "-0.00750",
    #       "price_unit": "USD",
    #       "sid": "SMded05904ccb347238880ca9264e8fe1c",
    #       "status": "sent",
    #       "subresource_uris": {
    #         "media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMded05904ccb347238880ca9264e8fe1c/Media.json",
    #         "feedback": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMded05904ccb347238880ca9264e8fe1c/Feedback.json"
    #       },
    #       "to": "+18182008801",
    #       "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMded05904ccb347238880ca9264e8fe1c.json"
    #     },
    #     {
    #       "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    #       "api_version": "2010-04-01",
    #       "body": "look mom I have media!",
    #       "date_created": "Fri, 24 May 2019 17:44:46 +0000",
    #       "date_sent": "Fri, 24 May 2019 17:44:49 +0000",
    #       "date_updated": "Fri, 24 May 2019 17:44:49 +0000",
    #       "direction": "inbound",
    #       "error_code": 30004,
    #       "error_message": "Message blocked",
    #       "from": "+12019235161",
    #       "messaging_service_sid": null,
    #       "num_media": "3",
    #       "num_segments": "1",
    #       "price": "-0.00750",
    #       "price_unit": "USD",
    #       "sid": "MMc26223853f8c46b4ab7dfaa6abba0a26",
    #       "status": "received",
    #       "subresource_uris": {
    #         "media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc26223853f8c46b4ab7dfaa6abba0a26/Media.json",
    #         "feedback": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc26223853f8c46b4ab7dfaa6abba0a26/Feedback.json"
    #       },
    #       "to": "+18182008801",
    #       "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc26223853f8c46b4ab7dfaa6abba0a26.json"
    #     }
    #   ],
    #   "start": 0,
    #   "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json?To=%2B123456789&From=%2B987654321&DateSent%3E=2008-01-02&PageSize=2&Page=0"
    # }




_keychain = _.regImp( __.appReg, 'keychain' )


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

# https://demo.twilio.com/welcome/sms/reply





