#!/bin/env python
# Import smtplib for the actual sending function
from __future__ import absolute_import, print_function, division
import smtplib
import os.path
import sys
from theano.misc.buildbot_filter import filter_output
# me == the sender's email address
# family = the list of all recipients' email addresses
family=['theano-buildbot@googlegroups.com']
me='lisa@iro.umontreal.ca'

#Those file contain the output of the do_nightly_build script.
files=["do_nightly_build_theano",
       "do_nightly_build_deeplearning",
       "do_nightly_build_theano_python3.3.0",
]
msgs=['Theano buildbot',
      'Deep Learning Tutorial buildbot',
      'Theano Python3.3.0 buildbot']

print('files', files)
print("msgs", msgs)
print("args", sys.argv)
if len(sys.argv) == 3:
    #We send just a file with a message
    files = [sys.argv[1]]
    msgs = [sys.argv[2]]
elif len(sys.argv) == 2:
    #This is a prefix where the output files are
    files=[os.path.join(sys.argv[1], x) for x in files]
else:
    files=[os.path.join('/tmp', x) for x in files]
print('path', files)

# Here are the email package modules we'll need
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

def mysend(subject, file):
    # Create the container (outer) email message.
    if not os.path.isfile(file):
        print("Error: no file", file)
        return

    msg = MIMEMultipart()
    msg['From'] = me
    msg['To'] = COMMASPACE.join(family)
    msg.preamble = 'The output of the buildbot'
    
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    with open(file, 'rb') as fp:
        s=fp.read()
    failures=0
    errors=0
    ran=False
    nb_ran=0
    skip=0
    speed_failure=0
    show_speed_failure=False
    knownfail=0
    gpu_time = None
    float32_time = None
    float64_time = None
    for token in s.split():
        token=token.strip('(,)')
        if token.startswith("failures="):
            failures+=int(token[9:])
        elif token.startswith("errors="):
            errors+=int(token[+7:])
        elif token == "Ran":
            ran=True
        elif token.startswith("SKIP="):
            skip+=int(token[5:])
        elif token == "KnownFailureTest:":
            # This means that KnownFailure plugin is off,
            # so knownfails are also counted as errors
            knownfail+=1
            errors-=1
        elif token.startswith("KNOWNFAIL="):
            knownfail += int(token.split('=')[1])
        elif token.startswith("speed_failure_"):
            speed_failure+=int(token.split('=')[1])
            show_speed_failure=True
        elif ran:
            ran=False
            try: 
                nb_ran+=int(token)
            except Exception as e:
                print(e)
                
    start = ""
    for line in s.splitlines():
        if gpu_time is None and line.startswith("gpu % expected/get"):
            start=line
        elif float32_time is None and line.startswith("float32 % expected/get"):
            start=line
        elif float64_time is None and line.startswith("float64 % expected/get"):
            start=line
        elif start:
            start+=line
            if start[-1]=="]":
                if start.startswith("gpu % expected/get"):
                    gpu_time = start
                    start = ""
                elif start.startswith("float32 % expected/get"):
                    float32_time = start
                    start = ""
                elif start.startswith("float64 % expected/get"):
                    float64_time = start
                    start = ""
    
    s = ("Summary of the output:\n\n" + filter_output(open(file)) +
         "\n\nFull output:\n\n" + s)
    img = MIMEText(s)
    msg.attach(img)
    
# Send the email via our own SMTP server.
    if show_speed_failure:
        msg['Subject'] = subject+" Fail="+str(failures)+" Err="+str(errors)+" Ran="+str(nb_ran)+" Skip="+str(skip)+" KnownFail="+str(knownfail)+ " SpeedFailure="+str(speed_failure)
    else:
        msg['Subject'] = subject+" Fail="+str(failures)+" Err="+str(errors)+" Ran="+str(nb_ran)+" Skip="+str(skip)+" KnownFail="+str(knownfail)

    print(msg['Subject'])
    s = smtplib.SMTP()
    s.connect()
    s.sendmail(me, family, msg.as_string())
    s.close()
    print("Finished sending email for", subject)

for msg, file in zip(msgs, files):
    mysend(msg, file)
