import android, time, os, ast
droid = android.Android()


#import os
import glob
import mimetypes 
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText



def attach_files(msg, xxxx):
  #print xxxx,'-------xxxxxx-------'
  for attachment in xxxx:
    attachment = attachment.strip()
    for path in glob.glob(attachment):
      filename = os.path.basename(path)
      if not os.path.isfile(path):
        continue
      # Guess the content type based on the file's extension.  Encoding
      # will be ignored, although we should check for simple things like
      # gzip'd or compressed files.
      ctype, encoding = mimetypes.guess_type(path)
      if ctype is None or encoding is not None:
        # No guess could be made, or the file is encoded (compressed), so
        # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
      maintype, subtype = ctype.split('/', 1)
      if maintype == 'text':
        fp = open(path)
        # Note: we should handle calculating the charset
        part = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
      elif maintype == 'image':
        fp = open(path, 'rb')
        part = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
      elif maintype == 'audio':
        fp = open(path, 'rb')
        part = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
      else:
        fp = open(path, 'rb')
        part = MIMEBase(maintype, subtype)
        part.set_payload(fp.read())
        fp.close()
        # Encode the payload using Base64
        encoders.encode_base64(part)
      # Set the filename parameter
      part.add_header('Content-Disposition', 'attachment', filename=filename)
      msg.attach(part)


def sendemail( smptS, smptP, email_name, email_user, email_pswd, mailto, subject, body, attachments):
  import smtplib

  smtp_server = smptS
  smtp_port = smptP

  # Build an SMTP compatible message
  msg = MIMEMultipart()
  msg['Subject'] = subject
  msg['To'] = mailto
  msg['From'] = email_name + " <" + email_user + ">"
  msg.attach(MIMEText(body, 'plain'))
  attach_files(msg, attachments)

  # Attempt to connect and send the email
  try:
    smtpObj = '' # Declare within this block.
    # Check for SMTP over SSL by port number and connect accordingly
    if( smtp_port == 465):
      smtpObj = smtplib.SMTP_SSL(smtp_server,smtp_port)
    else:
      smtpObj = smtplib.SMTP(smtp_server,smtp_port)
    smtpObj.ehlo()
    # StartTLS if using the default TLS port number
    if(smtp_port == 587):
      smtpObj.starttls()
      smtpObj.ehlo
    # Login, send and close the connection.
    smtpObj.login(email_user, email_pswd)
    smtpObj.sendmail(email_user, mailto, msg.as_string())
    smtpObj.close()
    return 1  # Return 1 to denote success!
  except Exception, err:
    # Print error and return 0 on failure.
    print err
    return 0
    
    
    
#---------------------------------------------------------

def dialogSpinnerProgress (title='--', text='--'):
  droid. dialogCreateSpinnerProgress (title, text)
  droid.dialogShow()
  return 'ready'
  
  
def dialogSpinnerProgress (title='--', text='--'):
  droid. dialogCreateSpinnerProgress (title, text)
  droid.dialogShow()
  return 'ready'
 

def dialogDismiss ():
  droid. dialogDismiss ()
  return 'ready'



#---------------------------------------------------------
def checkAirplaneMode ():  
  li = droid. checkAirplaneMode ().result
  return li    
def getRingerVolume ():
  li = droid. getRingerVolume ().result
  return li  
def getMediaVolume ():
  li = droid. getMediaVolume ().result
  return li     
def checkRingerSilentMode ():
  li = droid. checkRingerSilentMode ().result
  return li  
def checkScreenOn ():
  li = droid. checkScreenOn ().result
  return li  
def getScreenTimeout ():
  li = droid. getScreenTimeout ().result
  return li  
def getScreenBrightness ():
  li = droid. getScreenBrightness ().result
  return li  
def getVibrateMode ():
  li = droid. getVibrateMode ().result
  return li  
def checkWifiState ():
  li = droid. checkWifiState ().result
  return li
def checkBluetoothState ():
  li = droid. checkBluetoothState ().result
  return li    
def checkNetworkRoaming ():
  li = droid. checkNetworkRoaming ().result
  return li 

#---------------------------------------------------------  



def setScreenTimeout (tmp):
  li = droid. setScreenTimeout ( float (tmp) ).result
  return li  
def setRingerVolume (tmp):
  li = droid. setRingerVolume ( float (tmp) )
  return 'true'
def setScreenBrightness (tmp):
  li = droid. setScreenBrightness ( float (tmp) ).result
  return li   
def setMediaVolume (tmp):
  droid. setMediaVolume ( float (tmp) )
  li = droid. setMediaVolume ()
  return 'true'
  
def toggleAirplaneMode ():
  li = droid. toggleAirplaneMode() .result
  return li
def toggleWifiState ():
  li = droid. toggleWifiState () .result
  return li
def toggleRingerSilentMode ():
  li = droid. toggleRingerSilentMode () .result
  return li
def toggleBluetoothState ():
  li = droid. toggleBluetoothState () .result
  return li
def toggleVibrateMode ():
  li = droid. toggleVibrateMode () .result
  return li


#---------------------------------------------------------   
def getRunningPackages ():
  li = droid. getRunningPackages ().result  
  return li  
  
def getLaunchableApplications ():
  li = droid. getLaunchableApplications ().result  
  return li
#---------------------------------------------------------


#---------------------------------------------------------    
def dialogListChoice (title, butTxt , items, multSing ):
  droid.dialogCreateAlert(title)
  if multSing == 'single':
    droid.dialogSetSingleChoiceItems( items )
  else:
    droid.dialogSetMultiChoiceItems( items )    
  droid.dialogSetPositiveButtonText( butTxt )
  droid.dialogShow()
  response = droid.dialogGetResponse().result  
  if multSing == 'single':   
    response2 = droid.dialogGetSelectedItems().result
    retVal = response2 [0]
  else:
    retVal = str (droid.dialogGetSelectedItems().result)
    retVal = retVal.replace ('[','') 
    retVal = retVal.replace (']','')  
    if len ( retVal ) == 0 : retVal='-1'
  return  retVal
#---------------------------------------------------------


def alertWithBut ( title, message, posTxt, negTxt, neuTxt):
  droid.dialogCreateAlert(title, message)
  droid.dialogSetPositiveButtonText(posTxt)
  if len(negTxt)> 0 : droid.dialogSetNegativeButtonText(negTxt)
  if len(neuTxt)> 0 : droid.dialogSetNeutralButtonText(neuTxt)
  droid.dialogShow()
  li = droid.dialogGetResponse().result
  return li
  
def cameraCapturePicture ( picName, af ):
  droid. cameraCapturePicture ( picName, af  ) 
  return 'true'
      
def ping ():
  pass
  return 'true'  
  
def datePicker (year):
  droid.dialogCreateDatePicker(year)
  droid.dialogShow()
  date = droid.dialogGetResponse().result
  droid.dialogCreateAlert('xx', 'yy')
  li = str(date['day'])+','+str(date['month'])+',' + str(date['year'])
  return li  
                         
def timePicker():
  droid.dialogCreateTimePicker()
  droid.dialogShow()
  date = droid.dialogGetResponse().result
  droid.dialogCreateAlert('xx', 'yy')
  li = str(date['hour'])+','+str(date['minute'])+',' + str(date['which'])
  return li     
 
def getInput(title):
  li = droid. dialogGetInput (title).result
  return li   

def getPassword(title):
  li = droid. dialogGetPassword (title).result
  return li   
  
def sendMailStart (mdat):
  attach = mdat[8]
  sendemail(mdat[0], int(mdat[1]), mdat[2], mdat[3], mdat[4], mdat[5], mdat[6], mdat[7], [mdat[8]] )  
  return 'true'

  
def scanBarcode ():
  li = droid.scanBarcode ().result
  ret = li['extras']
  ret2 = ret['SCAN_RESULT']
  return ret2
  
  
def doEval ( str2calc, min, max, delta ):
  anzSteps = int((max-min)/delta +1)
  x        = min
  xx       = ''
  yy       = ''
  print x, anzSteps
  for i in range ( anzSteps ):
    xx += str (x) + '#'
    yy += str (eval ( str2calc )) + '#'
    x += delta
  
  vals = xx + '@' + yy
  return vals  
   
  
#---------------------------------------------------------
# main loop
#---------------------------------------------------------   
startTime  = time.asctime (time.localtime())
path       = '/sdcard/rfo-basic/data/'
fcmd       = path + 'basicCmd.txt'
fcmdReady  = path + 'basicCmdReady.txt'

flagBreak  = 0

while flagBreak==0:
  fe=0
  while fe==0:
    fe = os.path.exists( fcmdReady )
    time.sleep (0.1) 
   
  tic = time.time ()   
  
  fo  = open( fcmd , 'r+' )
  tmp = fo.read (20000)
  fo.close
    
  xxx = tmp.split ("#")
  curCmd = xxx [0] + '(' + xxx [1] + ')'
    
  print '----------------'
  print time.asctime (time.localtime())
  print tmp, xxx , curCmd
  print '--- --- --- -- --- --'
  
  li = eval( curCmd )
  fo = open( path + 'pyRtn.txt' , 'w')
  fo.write (str (li))
  fo.close ()  
  
  print li 
  dtEval = time.time () - tic
  print dtEval
  print '----------------'
  
  os.remove ( fcmd )
  os.remove ( fcmdReady )
  
  #time.sleep (5)







