#!/usr/bin/env python
import pika, subprocess, os, time

from datetime import date

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()


channel.queue_declare(queue='mail')

def callback(ch, method, properties, body):
    print("ID Proposta e liquidacao {body} Recebida".format(body=body))

    # producao
    p1 = subprocess.Popen(["php", "/var/www/html/Curl/sendmailcomprovante.php", body], stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
    # dev
    # p1 = subprocess.Popen(["php", "/var/www/html/Curl/sendmailcomprovante.php", body], stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
    out, err = p1.communicate()

    today = date.today()
    year = today.year
    month = today.month
    day = today.day
    file = open('/tmp/send_mail_comprovante_{year}{month}{day}.log'.format(year=year, month=month, day=day), 'w')
    if err:
        # p1 = subprocess.Popen(["python3", "send.py", body], stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
        # out, err = p1.communicate()

        print(err)
        file.write('{}'.format(err))

    if out:
        print(out)
        file.write('{}'.format(out))

    time.sleep(60)
channel.basic_consume('mail',
                      callback,
                      auto_ack=True)

print(' [*] Waiting for calls. To exit press CTRL+C')
channel.start_consuming()
