# -*- coding:utf-8 -*-
# @Time : 2019/10/8 14:47 
# @Author : litao
import redis,time,json,datetime,sys
from maintenance.func_send_email_with_file import send_file_email

rds = redis.StrictRedis(host='154.8.190.251', port=6379, db=19,decode_responses=True)


def write_email_task_to_redis(task_name=None,file_path=None, data_str=None, email_group=[],
                    email_msg_body_str=None,
                    title_str=None,
                    cc_group=[],sender=None):
    now = int(datetime.datetime.now().timestamp()*1e3)
    mapping_dic = {
            "taskname":task_name,
            "file_path":file_path,
            "data_str":data_str,
            "email_group":email_group,
            "email_msg_body_str":email_msg_body_str,
            "title_str":title_str,
            "cc_group":cc_group,
            "sender":sender
    }
    for k in mapping_dic:
        mapping_dic[k]=json.dumps(mapping_dic[k])
    rds.hmset(task_name+"%s_email" % now,mapping_dic)
    rds.rpush("email_task",task_name+"%s_email" %now)
    return True

def send_email_task_form_redis():
    task_name = rds.lpop("email_task")
    dic = rds.hgetall(task_name)
    send_file_email(
            json.loads(dic.get("file_path")),
            json.loads(dic.get("data_str")),
            email_group=json.loads(dic.get("email_group")),
            email_msg_body_str=json.loads(dic.get("email_msg_body_str")),
            title_str=json.loads(dic.get("title_str")),
            cc_group=json.loads(dic.get("cc_group")),
            sender=json.loads(dic.get("sender")),
    )
    rds.delete(task_name)
    print("task " + task_name + "done")
    return True

if __name__ == "__main__":
    # write_email_task_to_redis(task_name="1234",file_path=None,data_str="data_str",email_group=["litao@csm.com.cn"],email_msg_body_str="email_msg_body_str",title_str="title_str",sender="litao@csm.com.cn")
    now = datetime.datetime.now()
    while True and now.hour >= 5:
        try:
            if rds.llen("email_task") != 0:
                send_email_task_form_redis()
            else:
                print("wait for 5s")
                now = datetime.datetime.now()
                time.sleep(5)
        except:
            continue
    sys.exit(0)

