import random
import time
from concurrent.futures import ThreadPoolExecutor

from models.ips import Ips


def main(_, sql_info):
    import requests

    cookies = {
        'PHPSESSID': '8e48c4dd-69ef-561c-3082-e20564b88806',
        'ipsb': '3oMlNJzDmbhOQ7wtF96V451PWTxSvKfE',
    }

    headers = {
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'cache-control': 'no-cache',
        'dnt': '1',
        'pragma': 'no-cache',
        'referer': 'https://ip.sb/',
        'sec-ch-ua': '"Chromium";v="142", "Microsoft Edge";v="142", "Not_A Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'script',
        'sec-fetch-mode': 'no-cors',
        'sec-fetch-site': 'same-site',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0',
        # 'cookie': 'PHPSESSID=8e48c4dd-69ef-561c-3082-e20564b88806; ipsb=3oMlNJzDmbhOQ7wtF96V451PWTxSvKfE',
    }

    proxies = {
        'http': f'socks5://{sql_info.username}:{sql_info.password}@{sql_info.host}:{sql_info.port}',
        'https': f'socks5://{sql_info.username}:{sql_info.password}@{sql_info.host}:{sql_info.port}',
    }

    sql_info.country = None
    sql_info.start = None

    sql_info.save()

    for i in range(5):
        try:
            response = requests.get('https://ipv4.ip.sb/addrinfo', cookies=cookies, headers=headers, proxies=proxies)
            print(f"{_}，{response.json()}")

            sql_info.country = response.json()["country"]
            sql_info.start = 1

            sql_info.save()

            return
        except Exception as e:
            print(e)
            time.sleep(random.random())


if __name__ == '__main__':
    # proxies = {
    #     'http': f'socks5://127.0.0.1:{random.randint(42000, 42089)}',
    #     'https': f'socks5://127.0.0.1:{random.randint(42000, 42089)}',
    # }

    with ThreadPoolExecutor(max_workers=80) as executor:
        for _, i in enumerate(Ips.select()):
            executor.submit(main, _, i)
            time.sleep(random.random())

    # print(response.json())
