import logging
import pathlib
import time
import traceback
import uuid
from concurrent.futures import ThreadPoolExecutor

import requests

from reese84_bypass import Reese84ByPass

root_logger = logging.getLogger()

root_logger.setLevel(logging.WARNING)
root_logger.handlers = []
if not pathlib.Path('nacos-data/snapshot/').exists():
    pathlib.Path('nacos-data/snapshot/').mkdir(parents=True)


def check_pull():
    get_url = 'http://ymx-lcc.unififi.com/header/task/pull/cookieTR?brush_name=test'
    r = requests.get(get_url)
    return r.json()


def get_proxy():
    get_proxy_url = 'http://ymx-lcc.unififi.com/proxy/get-proxy'
    r = requests.post(get_proxy_url, json={
        'name': 'TR',
        'type': 'shopping'
    })
    return r.json()


def add_header(headers: dict, cookies: dict, px: str, thread_id=0):
    cks = []
    for k, v in cookies:
        cks.append(f'{k}={v}')
    headers['cookie'] = '; '.join(cks)
    data = {
        "brush_fromdate": "2023-06-19",
        "brush_fromto": "BOS-JFK",
        "brush_header": headers,
        "brush_name": f"reverse_{thread_id}",
        "brush_proxy": px,
        "brush_type": "cookieTR"
    }
    r = requests.post("http://ymx-lcc.unififi.com/header/add", json=data)
    print(r.json())


def exec(thread_id):

    while True:
        id_ = uuid.uuid4().hex
        pull = check_pull()
        try:
            if pull.get('status') == 1:
                print('休眠十秒')
                time.sleep(10)
                continue
        except:
            pass

        try:
            px = get_proxy()['url']
            cf = Reese84ByPass(target="https://www.flyscoot.com/", proxy=px, thread_name=f'{thread_id}')
            headers, cookies = cf.start()
            # cf.test()
            add_header(headers, cookies, px, thread_id)
        # except json.decoder.JSONDecodeError:
        #     print('json huoqu shibai ')
        except Exception as e:
            print(e)
            traceback.print_exc()


def run():
    brush_thread = 3

    print(f'本次并发数 {brush_thread}')

    # pool = ThreadPoolExecutor(max_workers=brush_thread)
    # all_task = [pool.submit(exec, (i)) for i in range(brush_group)]
    # brush_check = CONFIG['internal']['reverse']['making']['brush_check']
    # wait(all_task, return_when=ALL_COMPLETED)
    # print(f'休息 {brush_check} 秒')
    # time.sleep(brush_check)

    with ThreadPoolExecutor(max_workers=brush_thread) as executor:
        objs = []
        for t in range(1, brush_thread + 1):
            task = executor.submit(exec, t)
            objs.append(task)
        while 1:
            time.sleep(1)
            for n, o in enumerate(objs):
                if o.done():
                    task = executor.submit(exec, n + 1)
                    objs[n] = task


if __name__ == '__main__':
    run()
