import smtplib
import sys
from email.message import EmailMessage
import ci_secrets
import os


def run(tp_file,od_file,coop):
    msg = EmailMessage()
    msg['Subject'] = "Coopdev : évolutions à tester"
    msg['From'] = "brevo@ksuite-coopdev.fr"
    msg['To'] = ci_secrets.coops_mails[coop]
    msg['CC'] = "assistance-redmine@coopdev.fr"
    msg['Reply-to'] = "assistance-redmine@coopdev.fr"

    tp_file_exists = os.path.exists(tp_file)
    od_file_exists = os.path.exists(od_file)

    if not tp_file_exists and not od_file_exists:
        print("MAIL : rien à envoyer")
        return
    elif not tp_file_exists:
        tp_file = "/home/django/third-party/scripts/data/ci_diff_third-party_last.txt"
        tp_file_exists = os.path.exists(tp_file)
    elif not od_file_exists:
        od_file = "/home/django/third-party/scripts/data/ci_diff_Odoo_last.txt"
        od_file_exists = os.path.exists(od_file)

    body = "Bonjour " + ci_secrets.coops_usernames[coop] +",\n\n"
    body = body + "De nouveaux développements en attente de mise en production ont été mis en ligne sur " + ci_secrets.coops_preprod_urls[coop] + ".\n"
    body = body + "On te remercie de bien vouloir tester ces évolutions et de nous faire un retour via les liens redmine ci-dessous (si possible), ou en répondant à assistance-redmine@coopdev.fr." + "\n\n\n"
    if tp_file_exists:
        tp_f = open(tp_file,"r")
        body = body + "Evolutions des applications tierces :\n\n" + tp_f.read() + "\n\n"
        tp_f.close()
    if od_file_exists:
        od_f = open(od_file,"r")
        body = body + "Evolutions d'odoo :\n\n" + od_f.read() + "\n\n"
        tp_f.close()
    body = body + "Coopérativement.\nCoopdev Foodcoops"
    msg.set_content(body)
    s = smtplib.SMTP('smtp-relay.sendinblue.com', port=587)
    s.login("brevo@ksuite-coopdev.fr", ci_secrets.mail_server_password)
    s.send_message(msg)
    s.quit()
    print("MAIL : envoi effectué")

if __name__ == '__main__':
    arg = ""
    if len(sys.argv) > 3:
        arg1 = sys.argv[1]
        arg2 = sys.argv[2]
        arg3 = sys.argv[3]
    run(arg1,arg2,arg3)
