import requests
import pymysql
import random
from log_settings import *
import traceback
import logging
import datetime
from auto_request import get_offline_comment
from auto_request import host, user, db, passwd

auto_reply_url = "http://saturn.iyanzhi.com/api/v1/reply/create_for_inner"


def reply(id, content, user_id):
    try:
        post_dict = {
            'user_id': user_id,
            'topic_id': id,
            'content': content,
            "type": 4
        }
        response = requests.post(url=auto_reply_url,
                                 data=post_dict)

        logging.info("response.text:%s" % response.text)

    except:

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


def get_data(now, noww):
    try:
        pc = pymysql.connect(host=host, user=user, passwd=passwd, db=db, port=3306)
        cursor = pc.cursor()
        cursor.execute(
            "SELECT id,user_id  FROM topic WHERE ( create_time > '%s' and  create_time <= '%s' )  and is_online = 1  and  content_level in (4,5,6) " % (
                now, noww))
        data = cursor.fetchall()
        topic_id = list(data)
        topic_id_list = []
        for id in topic_id:
            cursor.execute(
                "select user_id from user_extra where user_id =" + str(id[1]) + " and is_shadow =1")
            data = cursor.fetchall()
            user_id = list(data)
            if user_id:
                topic_id_list.append(i)
        pc.close()
        logging.info("get topic_id_list:%s" % topic_id_list)
        return topic_id_list
    except:
        logging.error("catch exception,get_data:%s" % traceback.format_exc())
        return None


if __name__ == "__main__":

    try:

        now = datetime.datetime.now()
        yes_time = now - datetime.timedelta(minutes=5)
        user_data = open("/data/log/cybertron/app/user_id.txt", "r")
        user_list = []
        for i in user_data.readlines():
            user_list.append(i)
        topic_id = get_data(yes_time, now)
        dicts = {}
        if topic_id:
            for id in topic_id:
                rand_num = random.randint(1, 3)
                for i in range(rand_num):
                    num = random.randint(0, len(user_list) - 1)
                    user_id = user_list[num]
                    if user_id != id[1]:
                        comment_list = get_offline_comment()
                        comment = comment_list[i]
                        reply(id[0], comment, user_id)
    except:
        logging.error("catch exception,main :%s" % traceback.format_exc())