#!/bin/env/python
# coding: utf8

import pandas as pd
import chardet
import glob
import sys, os

def readCSV(file):
    """
    Read CSV file
    """
    data=pd.read_csv(file)
    return data

def writeCSV(data,file):
    """
    Write CSV file
    """
    data.to_csv(file)
    return

def addColToCSV(data,outputfile,value):
    """
    Add column to CSV file
    """
    ncol=10
    data.insert(ncol,'Présence',value)
    data.to_csv(outputfile)
    return

def upperFirst(x):
    return x[0].upper() + x[1:]

def makeAttendanceList(data,titre,date):
    """
    Generates a list to be signed by participants
    """

    tmp = "sign.tex"
    texfile = open(tmp,'w')

    contents = """\\documentclass[12pt]{report}

\\usepackage[landscape]{geometry}
\\usepackage[francais]{babel}
\\usepackage[utf8]{inputenc}

\\usepackage{longtable}

\\begin{document}

\\begin{center}
{\\bf \\large
LyonCalcul
\\\\[1em]
}

TITRE

DATE
\\end{center}

\\renewcommand{\\arraystretch}{3.0}
\\begin{longtable}{|p{0.20\\linewidth}|p{0.25\\linewidth}|p{0.28\\linewidth}|p{0.22\\linewidth}|}
\\hline
    """

    replaced_contents = contents.replace('TITRE', titre)
    contents = replaced_contents.replace('DATE', date)
    texfile.write(contents)
    texfile.close()

    for n in range(len(data)):
        prenom = data.loc[data.index[n],"Prénom"].strip()
        prenom = upperFirst(prenom)
        nom = data.loc[data.index[n],"Nom"].strip().upper()
        lab = data.loc[data.index[n],"Laboratoire"].strip()

        texfile = open(tmp,'a')
        texfile.write("%s & %s & %s & \\\\ \n"%(prenom,nom,lab))
        texfile.write("\hline \n")
        texfile.close()

    #end for
    texfile = open(tmp,'a')
    contents = """\end{longtable}
\end{document}
    """
    texfile.write(contents)
    texfile.close()

    return

def makeAttestation(data,titre,date,heures,path):
    """
    Generates the letter for participation
    """
    
    template = path + "templateAttestation.tex"
    tex = "Attestation_" 

    for n in range(len(data)):
        prenom = data.loc[data.index[n],"Prénom"].strip().replace(" ","-")
        nom = data.loc[data.index[n],"Nom"].strip().replace(" ","-")

        texfile = open(template)
        tmp = texfile.read()
        name = prenom + " " + nom
        tmp = tmp.replace('PATH', path)
        tmp = tmp.replace('NAME', name)
        tmp = tmp.replace('TITRE', titre)
        tmp = tmp.replace('DATE', date)
        tmp = tmp.replace('HEURES', heures)
        replaced_contents = tmp

        OutputFileName = tex + prenom + "_" + nom + ".tex"

        resFile = open(OutputFileName,'w')
        resFile.write(replaced_contents)
        resFile.close()

    for file in glob.glob("Attestation*.tex"):
        print(file)
        os.system('pdflatex %s' % file)

    return

def SendMail(prenom,nom,mail,subject,body,fromaddr,login,passwd):
    """
    Send simple mail
    """

    import smtplib

    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
	
    toaddr = mail
	
    print("Mail sent to : %s"%mail)
	
    msg = MIMEMultipart()
    msg["From"] = fromaddr
    msg["To"] = toaddr
    msg["Subject"] = subject

    msg.attach(MIMEText(body, "plain", "utf-8"))
  
    server = smtplib.SMTP('smtp.ec-lyon.fr', 587)
    server.starttls()
    server.login(login,passwd)
    text = msg.as_string()
    #encoding=chardet.detect(text)['encoding']
    #print(encoding)
    #if encoding != 'ascii':
    #   text = text.decode(encoding, text).encode('utf-8')
    #else:
    #    text = msg.as_string().encode('ascii')
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

    return

def SendMailFile(prenom,nom,mail,subject,body,filename,fromaddr,login,passwd):
    """
    Send mail with attestation
    """

    import smtplib

    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email import encoders
	
    toaddr = mail
    print("Mail sent to : %s"%mail)
	
    msg = MIMEMultipart()
    msg["From"] = fromaddr
    msg["To"] = toaddr
    msg["Subject"] = subject

    msg.attach(MIMEText(body, "plain", "utf-8"))

    attachment = open(filename, "rb")

    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
 
    msg.attach(part)
  
    server = smtplib.SMTP('smtp.ec-lyon.fr', 587)
    server.starttls()
    server.login(login,passwd)
    text = msg.as_string()
    #encoding=chardet.detect(text)['encoding']
    #print(encoding)
    #if encoding != 'ascii':
    #   text = text.decode(encoding, text).encode('utf-8')
    #else:
    #    text = msg.as_string().encode('ascii')
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

    return

def makeMail(data,subject,text,fromaddr,login,passwd):
    """
    Send mail to the list
    """

    for n in range(len(data)):
        prenom = data.loc[data.index[n],"Prénom"].strip()
        nom = data.loc[data.index[n],"Nom"].strip()
        mail = data.loc[data.index[n],"Courriel"].strip()
        #mail = "anne.cadiou@gmail.com"

#        body = "Bonjour %s %s,\n\n%s\
#La journée LyonCalcul R/Pandas aura bien lieu demain\n\
#Salle René Michel, Bâtiment OMEGA, Université Claude Bernard Lyon 1.\n\n\n\
#Cordialement,\n\
#Anne Cadiou\n"%(prenom,nom,text)

        body = "Bonjour %s %s,\n\n\
La journée LyonCalcul R/Pandas aura bien lieu demain\n\
Salle René Michel, Bâtiment OMEGA, Université Claude Bernard Lyon 1.\n\
- message généré grâce à Pandas :-)\n\n\n\
Cordialement,\n\
Anne Cadiou et Bastien Di Pierro\n"%(prenom,nom)


        SendMail(prenom,nom,mail,subject,body,fromaddr,login,passwd)

    return

def sendAttestation(data,subject,text,fromaddr,login,passwd,titre,date):
    """
    Send the attestations to the list if valid
    """
   
    tex = "Attestation_" 

    for n in range(len(data)):
        prenom = data.loc[data.index[n],"Prénom"].strip().replace(" ","-")
        nom = data.loc[data.index[n],"Nom"].strip().replace(" ","-")
        filename = tex + prenom + "_" + nom + ".pdf"

        prenom = data.loc[data.index[n],"Prénom"].strip()
        nom = data.loc[data.index[n],"Nom"].strip()
        mail = data.loc[data.index[n],"Courriel"].strip()
        mail = "anne.cadiou@gmail.com"
        body = "Bonjour %s %s,\n\n\
Voici votre attestation de participation à la %s de LyonCalcul du %s.\n\n\
Cordialement,\n\
Anne Cadiou\n"%(prenom,nom,titre,date)

        if data.loc[data.index[n],"Présence"] == 1:
            SendMailFile(prenom,nom,mail,subject,body,filename,fromaddr,login,passwd)
        else:
            print("%s %s était absent"%(prenom,nom))

    return


if __name__ == '__main__':
    main()



