import requests
import time
import datetime
import random
import traceback
import logging

auto_click_url = "http://earth.iyanzhi.com/api/v1/like"
auto_reply_url = "http://earth.iyanzhi.com/api/v1/reply/create"
auto_follow_url = "http://earth.iyanzhi.com/api/v1/follow"
auto_urge_url = "http://earth.iyanzhi.com/api/v1/user/urge"

# auto_click_url = "http://earth.igengmei.com/api/v1/like"
# auto_reply_url = "http://earth.igengmei.com/api/v1/reply/create"
# auto_follow_url = "http://earth.igengmei.com/api/v1/follow"
# auto_urge_url = "http://earth.igengmei.com/api/v1/user/urge"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'alpha',
        'USER': 'work',
        'PASSWORD': 'Gengmei123',
        'HOST': 'rm-2zeaut61u9sm21m0b.mysql.rds.aliyuncs.com',
        'PORT': '3306',
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;",
            "charset": "utf8mb4",
        },
    }
}

host = DATABASES['default']['HOST']

user = DATABASES['default']['USER']

port = DATABASES['default']['PORT']

db = DATABASES['default']['NAME']

passwd = DATABASES['default']['PASSWORD']


def get_majia():
    try:
        data = open("/srv/apps/cybertron/batch_user_gen")
        list = []
        for i in data:
            list.append(i.strip('\n').strip(','))
        maj = random.randint(1, len(list))
        user_id = list[maj - 1]
        return user_id

    except:
        logging.error("catch exception,get_majia:%s" % traceback.format_exc())
        return None


def get_cookies(user_id):
    try:
        with open("/srv/apps/cybertron/user_session.txt", 'r') as f:
            try:
                data = f.readlines()
            except:
                data = None

        list = []
        for i in data:
            list.append(i.strip('\n').split(","))

        for i in list:

            if user_id == i[0]:
                return (i[1])
    except:

        return None


def login():
    try:
        user_id = get_majia()

        cookies = get_cookies(user_id)

        if cookies is not None:
            return {'sessionid': cookies}

    except:

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

        return None


def click(cookies_get, id):
    try:
        post_dict = {
            'type': 0,
            'id': id
        }
        response = requests.post(url=auto_click_url,
                                 cookies=cookies_get,
                                 data=post_dict)

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

    except:

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


def reply(cookies_get, id, content):
    try:
        post_dict = {
            'topic_id': id,
            'content': content
        }
        response = requests.post(url=auto_reply_url,
                                 cookies=cookies_get,
                                 data=post_dict)

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

    except:

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


def time_conv(minutest):
    try:
        now = datetime.datetime.now()
        yes_time = now - datetime.timedelta(minutes=minutest)
        return yes_time

    except:
        return None


def time_convs(numtime, numtime2):
    try:
        now = datetime.datetime.now()

        yes_time = now - datetime.timedelta(days=numtime)
        yes_time_str = yes_time.strftime('%Y-%m-%d')
        yes_time_str = yes_time_str + ' 23:59:59.000000'

        yes_time2 = now - datetime.timedelta(days=numtime2)
        yes_time_str2 = yes_time2.strftime('%Y-%m-%d')
        yes_time_str2 = yes_time_str2 + ' 00:00:00.000000'

        return yes_time_str, yes_time_str2
    except:
        return None


def get_comment():
    try:
        data = open("/srv/apps/cybertron/guanshui", "r")
        list_guanshui = []
        for i in data:
            list_guanshui.append(i)

        num = random.randint(0, len(list_guanshui))

        comment = list_guanshui[num - 1]

        return comment

    except:

        return None


def get_comments():
    try:
        data = open("/srv/apps/cybertron/guanshui", "r")
        list_guanshui = []
        for i in data:
            list_guanshui.append(i)

        num1 = random.randint(0, 50)
        num2 = random.randint(50, 70)
        num3 = random.randint(70, len(list_guanshui))

        comment1 = list_guanshui[num1 - 1]
        comment2 = list_guanshui[num2 - 1]
        comment3 = list_guanshui[num3 - 1]

        comment_list = [comment1, comment2, comment3]

        return comment_list

    except:

        return None


def follow(cookies_get, id):
    try:
        post_dict = {
            'type': 1,
            'id': id
        }
        response = requests.post(url=auto_follow_url,
                                 cookies=cookies_get,
                                 data=post_dict)

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

    except:

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


def Urge(cookies_get, id):
    try:
        post_dict = {
            'id': id
        }
        response = requests.post(url=auto_urge_url,
                                 cookies=cookies_get,
                                 data=post_dict)

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

    except:

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


def get_offline_comment():
    try:
        data = open("/srv/apps/cybertron/comment.txt", "r")

        list_guanshui = []
        for i in data:
            list_guanshui.append(i)
        num1 = random.randint(0, 500)
        num2 = random.randint(500, 1000)
        num3 = random.randint(1000, 1500)
        num4 = random.randint(1500, len(list_guanshui))

        comment1 = list_guanshui[num1 - 1]
        comment2 = list_guanshui[num2 - 1]
        comment3 = list_guanshui[num3 - 1]
        comment4 = list_guanshui[num4 - 1]

        comment_list = [comment1, comment2, comment3, comment4]
        return comment_list

    except:

        return None


# def logins():
#     try:
#         user_id = get_majia()
#
#         cookies = get_cookies(user_id)
#
#         if cookies is not None:
#             return {'sessionid': cookies}
#
#     except:
#
#         logging.error("catch exception,logins:%s" % traceback.format_exc())
#
#         return None

def get_user_id():
    user_data = open("user_id.txt", "r")
    user_list = []

    for i in user_data.readlines():
        user_list.append(int(i.strip()))

    return user_list