import requests
import tls_client
from pyquery import PyQuery


def get_header():
    r = requests.post('http://ymx-lcc.unififi.com/header/borrow', json={
        "brush_type": "cookieAS",
        "brush_fromto": "aaa-bbb",
        "method": "shopping"
    })
    return r.json()


def return_header(header):
    r = requests.post('http://ymx-lcc.unififi.com/header/return', json={
        "brush_type": "cookieTR",
        "_id": header['brush_id'],
        "status": 0,
    })
    print(r.text)


def test():
    header = get_header()
    headers = header['data']['brush_header']
    # headers.update({
    #     "content-type": "application/json",
    #     "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    # })
    # headers.update({
    #         "authority": "makeabooking.flyscoot.com",
    #         "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    #         "accept-language": "en-US,en;q=0.9",
    #         "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
    #     })
    brush_proxy = header['data']['brush_proxy']
    session = tls_client.Session(client_identifier='chrome_117')
    # session.proxies = {
    #     'http': 'http://127.0.0.1:7890',
    #     'https': 'http://127.0.0.1:7890',
    # }
    session.proxies = {
        'http': brush_proxy,
        'https': brush_proxy,
    }
    print(headers)
    print(brush_proxy)
    url = "https://makeabooking.flyscoot.com/Book/Flight?culture=en-SG&type=oneway&dst1=SIN&ast1=ADL&dst2=ADL&ast2=SIN&dd=2023-12-15&rd=null&adt=1&chd=0&inf=0#"
    # url = "https://makeabooking.flyscoot.com/Book/Flight?culture=en-SG&type=oneway&dst1=SIN&ast1=ADL&dst2=ADL&ast2=SIN&dd=2023-12-18&rd=null&adt=1&chd=0&inf=0"
    # response = session.get(url, headers=headers)
    response = requests.post('http://52.52.23.116/tls/forward',
                             # response = requests.post('http://127.0.0.1:58000/tls/forward',
                             json=dict(url=url, headers=headers, method="GET", proxy=session.proxies['http'],
                                       debug=True, )

                             , allow_redirects=True
                             )
    print(response.json()['text'])
    print(response.json()['status_code'])
    h = PyQuery(response.json()['text'])
    # print(response.status_code)
    # h = PyQuery(response.text)
    print(h.find('iframe[id="main-iframe"]').attr('src'))
    r1 = session.get('https://makeabooking.flyscoot.com' + h.find('iframe[id="main-iframe"]').attr('src'),
                     headers=headers)
    print(r1.text)
    r2 = session.get(url, headers=headers)
    print(r2.text)
    return_header(header['data'])


if __name__ == '__main__':
    test()
