import pymysql
import traceback
import logging
import json
from log_settings import *
from auto_request import logins, reply, get_comment, time_conv, get_answer_data, reply_answer, set_reply_to_redis, \
    get_majia
from auto_request import host, user, db, passwd


def get_data(numtime, numtime2):
    try:
        pc = pymysql.connect(host=host, user=user, passwd=passwd, db=db, port=3306)
        cursor = pc.cursor()
        cursor.execute(
            "SELECT  user_id,id FROM topic WHERE is_online=1  and (create_time > '%s' and create_time < '%s' )" % (
                numtime, numtime2))
        data = cursor.fetchall()
        topic_id = list(data)
        topic_id_list = []
        try:
            for i in topic_id and topic_id:
                cursor.execute(
                    "select user_id from user_extra where user_id =" + str(i[0]) + " and is_shadow =0")
                data = cursor.fetchall()
                user_id = list(data)
                if user_id:
                    topic_id_list.append(i)
            logging.info("Database version : %s " % topic_id_list)
            pc.close()

        except:
            logging.error("catch exception,get_data:%s" % traceback.format_exc())

        return topic_id_list

    except:
        logging.error("catch exception,get_data:%s" % traceback.format_exc())
        return []


if __name__ == "__main__":

    try:
        logging.info("comment  answer one")
        numtime1, numtime2 = time_conv(45, 35)
        user_id = get_data(numtime1, numtime2)
        redis_key1 = "cybertron:set_reply_id:three"
        reply_data_comment = []
        if user_id:
            for i in user_id:
                majia_user_id = get_majia()
                cook = logins(majia_user_id)
                comment1, comment2 = get_answer_data()
                if cook is not None:
                    response = reply_answer(cook, i[1], comment1)
                    if len(response) > 1:
                        data_dict = json.loads(response)
                        reply_id = data_dict["data"]["id"]
                        reply_user_id = data_dict["data"]["user"]["id"]
                        reply_data_comment.append(
                            {"id": reply_id, "reply_user_id": reply_user_id, "answer": comment2, "topic_id": i[1],
                             "majia_user_id": majia_user_id})

        redis_client = set_reply_to_redis()
        redis_client.set(redis_key1, json.dumps(reply_data_comment))

    except:
        logging.error("catch exception,main:%s" % traceback.format_exc())