#!/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():
    pass
    _.switches.register( 'To', '-to' )
    _.switches.register( 'Body', '-body' )

_.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-send.py',
    'liveAppName': __.thisApp( __file__ ),
     'description': 'send sms messages',
    'categories': [
                        'twilo',
                        'sms',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p vps-srv-7facG-twilio-send '),
                        '',
    ],
    '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

names = {
                '8136901260': 'Scott',
                '8139095297': 'Alexandria',
                '8138384321': 'Taylor',
                '8134695709': 'Beth',
                '8136101963': 'Jon',
                '8132449301': 'Mema',
                '8136245009': 'Grandpa',
                '8137354872': 'Jessica',
                '7275121425': 'Kevin',
                '7279023028': 'Karla',
                '8139573524': 'Lorraine',
                '8135035938': 'Frank',
                '7755356008': 'EyeForMeta',
}

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

def format_number(string):
    string=str(string)
    tmp=''
    for x in string:
        if x in '0123456789':
            tmp+=x
    if not tmp.startswith('1'):
        tmp='1'+tmp
    if not tmp.startswith('+'):
        tmp='+'+tmp
    return tmp
def action( to='813-690-1260', from_='775-535-6008', body='thank you' ):
    to = format_number(to); from_ = format_number(from_);
    if _.switches.isActive('To'):
        to = _.switches.values('To')[0]
    if _.switches.isActive('Body'):
        body = ' '.join(_.switches.values('Body'))
    global names
    if type(to) == int:
        to = str(to)
    if not '+1' in to:
        to = '+1' + to
    too = to.replace('+1','')
    if too in names:
        body = body.replace( 'TO', names[too] )
    if from_ in names:
        body = body.replace( 'FROM', names[from_] )

    # 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 = 'ACf0681c27423f534c58bb90aa34f36b42'
    auth_token = '28776639e6e86e6f50497a3dfc1c1064'
    client = Client(account_sid, auth_token)

    message = client.messages \
                    .create(
                         body=body,
                         from_='+17755356008',
                         to=to
                     )

    _.pr(message.sid)
    # for x in dir(client.messages):
    #     _.pr(x)
    # EXAMPLE JSON RESPONSE
    # {
    #   "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    #   "api_version": "2010-04-01",
    #   "body": "Join Earth's mightiest heroes. Like Kevin Bacon.",
    #   "date_created": "Thu, 30 Jul 2015 20:12:31 +0000",
    #   "date_sent": "Thu, 30 Jul 2015 20:12:33 +0000",
    #   "date_updated": "Thu, 30 Jul 2015 20:12:33 +0000",
    #   "direction": "outbound-api",
    #   "error_code": null,
    #   "error_message": null,
    #   "from": "+15017122661",
    #   "messaging_service_sid": "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    #   "num_media": "0",
    #   "num_segments": "1",
    #   "price": null,
    #   "price_unit": null,
    #   "sid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    #   "status": "sent",
    #   "subresource_uris": {
    #     "media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
    #   },
    #   "to": "+15558675310",
    #   "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
    # }




# https://www.twilio.com/docs/sms/quickstart/python

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





