#!/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( 'Input', '-i' )
    pass

#   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-7GT90c-bot-chat.py',
    'liveAppName': __.thisApp( __file__ ),
     'description': 'chat bot for client 7i0ZA project 7GT90c',
    'categories': [
                        'chat',
                        'bot',
                        'vps',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('/usr/bin/python3 /opt/rightthumb-widgets-v0/widgets/python/vps-hoth-7i0ZA-7GT90c-bot-chat'),
                        '',
    ],
    '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 )
    # _.switches.trigger( 'Files',_.inRelevantFolder )  
    
    _.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


def cleanBE(data,what):
    while data.endswith(what):
        data=data[:-1]
    while data.startswith(what):
        data=data[1:]
    return data

def clean(data):
    data = data.replace('\r','')
    i=0
    while not i == 10:
        i+=1
        data = cleanBE(data,' ')
        data = cleanBE(data,'\t')
        data = cleanBE(data,'\n')
    return data

def extractMSG(msg):
    # _.pr('______________________________________')
    # _.pr([msg])
    _.pr('______________________________________')
    _.pr(len(msg))
    _.pr(type(msg))
    _.pr('______________________________________')
    started=False
    lines = []
    for line in msg.split('\n'):
        if started:
            if '--00000' in line:
                started=False
        if started:
            if not line.startswith('Content-'):
                lines.append(line)
        if not started and 'Content-Type' in line and 'text/plain' in line:
            started=True

    message = '\n'.join(lines)
    message = clean(message)
    _.pr('message',message)
    return message



import poplib
from email.parser import Parser

import smtplib, ssl


class Gmail():
    def __init__( self ):
        self.port = 465
        self.host = "smtp.gmail.com"
        self.sender = "Tampa.Bay.Generators.7i0ZA@gmail.com"
        self.password = '2aACQU7WBAaOr1ET2fVlEXzs4mOzZbfzcTN8z7Wzn7njPwpfO9b8bA=='
        self.server=None

    def login( self ):
        try:
            context = ssl.create_default_context()
            self.server = smtplib.SMTP_SSL(self.host, self.port, context=context)
            self.server.login(   self.sender,   _vault.s.de(self.password)   )
        except Exception as e:
            _.e('gmail',e)
        _.pr('gmail, login')


    def talk( self, to, msg ):

        try:
            self.server.sendmail(self.sender, to, msg)
        except Exception as e:
            self.login()
            self.server.sendmail(self.sender, to, msg)
        _.pr('gmail, sent,',to)


class VPS():
    def __init__( self ):
        self.spent = []
        self.server=None
        self.first=True

        self.login()
        self.listen()

    def login_run( self ):
        email = 'brenda@eyeformeta.com'
        password = 'Pb9sT9htevI/qyLr8MrA2Q=='
        pop3_server = 'mail.eyeformeta.com'
        self.server = poplib.POP3(pop3_server)
        self.server.set_debuglevel(1)
        pop3_server_welcome_msg = self.server.getwelcome().decode('utf-8')
        # print out the pop3 server welcome message.
        _.pr(self.server.getwelcome().decode('utf-8'))
        # user account authentication
        self.server.user(email)
        self.server.pass_(  _vault.s.de(password)  )
        # stat() function return email count and occupied disk size
        _.pr('Messages: %s. Size: %s' % self.server.stat())

    def login( self ):
        try:
            return self.login_run()
        except Exception as e:
            _.e('vps, login',e)
        _.pr('vps, login')

    def listen( self, fro=None ):
        try:
            return self.listen_run(fro)
        except Exception as e:
            _.e('vps, listen',e)


    def listen_run( self, fro=None ):
        i=0
        while True:
            self.login()
            i+=1
            _.pr('vps, listen', fro, i)

            try:
                resp, mails, octets = self.server.list()
            except Exception as e:
                self.login()
                resp, mails, octets = self.server.list()
            # _.pr(mails)
            index=0
            while not index == len(mails):
                index+=1
                resp, lines, octets = self.server.retr(index)
                msg_content = b'\n'.join(lines).decode('utf-8')
                msg = Parser().parsestr(msg_content)
                dic = {
                            'id': msg.get('message-id'),
                            'from': msg.get('From'),
                            'to': msg.get('To'),
                            'subject': msg.get('Subject'),
                            # 'message': extractMSG(str(msg)),
                }
                if self.first:
                    self.check(dic['id'])
                else:
                    if self.check(dic['id']):
                        if fro is None:
                            return extractMSG(str(msg))
                        elif fro == dic['from']:
                            _.cp(dic['from'],'green')
                            return extractMSG(str(msg))

            if self.first:
                self.first = False
                return None
            pass
            time.sleep(10)
            self.server.quit()
            # return ''
            # 

    def check( self, subject ):
        if not subject in self.spent:
            self.spent.append(subject)
            return True
        return False



class Bot():
    def __init__( self ):
        self.gmail=Gmail()
        self.vps=VPS()
        self.first='Hello NAME, my name is Brenda.\n\nHow would you like to be greeted?\n\nname, random, endearing, mean, sexy, mf, none'
        self.help='you can reply:\nzip 33624\nsettings\nreports\ne or expecting\ntype ? or help at any time'
        self.prefixes='zip setting report ? expecting'.lower().split(' ')
        self.users = {}

        # self.users = _.getTable('vps-hoth-7i0ZA-7GT90c-bot-chat.hash')
        self.expecting={}

        if not self.users:
            self.users={}
            self.add( 'Scott', '8136901260@vtext.com' )

        for e in self.users:
            self.expecting[e]=self.help
            if self.users[e]['greeting'] is None:
                self.settings(e)
            
        


    def settings( self, e ):
        self.users[e]['greeting']=self.ask(e,self.first.replace('NAME',self.users[e]['name']['first']), 'greeting prefrence:\n\nname, random, endearing, mean, sexy, mf, none')
        _.pv(self.users)
        self.gmail.talk(e,self.greeting( self.users[e]['name']['first'], self.users[e]['greeting'], test=True ))
        self.gmail.talk(e,self.greeting( self.users[e]['name']['first'], self.users[e]['greeting'], test=True ))
        self.gmail.talk(e,self.greeting( self.users[e]['name']['first'], self.users[e]['greeting'], test=True ))
        
        greeting=self.greeting( self.users[e]['name']['first'], self.users[e]['greeting'] )
        self.gmail.talk(e,greeting+self.help)
        
        _.saveTable( self.users, 'vps-hoth-7i0ZA-7GT90c-bot-chat.hash' )


    def responses( self, e, subject ):
        if subject == 'expecting':
            return None
        self.gmail.talk(e,self.help)
        return None





    def ask( self, e, ask, expecting='' ):
        self.expecting[e]=expecting
        self.gmail.talk(e,ask)
        answer = self.vps.listen(e).lower()
        for pre in self.prefixes:
            if answer.startswith(pre):
                self.responses( e, answer )
                return self.ask( e, ask, expecting )
            elif answer=='e' or answer=='help':
                self.responses( e, 'expecting' )
                return self.ask( e, ask, expecting )
        self.expecting[e]=self.help
        return answer






    def greeting( self, name, ty, test=False ):
        _greeting.imp.name=name
        if not test:
            _greeting.switch('Random','')
            _greeting.switch('Random',delete=True)
        else:
            _greeting.switch('Random','time')
        _greeting.switch('Type',ty)
        if ty == 'random':
            _greeting.switch('Random','type')

        g=_greeting.action()
        if len(g):
            g+='\n\n'
        return g


    def add( self, name, email ):
        if not email in self.users:
            self.users[email]={}
            self.users[email]['email']=email
            self.users[email]['name']={}
            self.users[email]['name']['first']=name
            self.users[email]['greeting']=None




def action():
    bot = Bot()


import _rightThumb._vault as _vault
_greeting = _.regImp( __.appReg, 'greeting' )



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





