import log4js from 'log4js'
import {bl, genUuid, ht, ie, Ol, randint, se} from "./utils.js"
import axios from "axios";
import {PxEnv} from './px.js'
import {MongoClient} from "mongodb";

const uri = "mongodb://lcc-spider:JIUsfhiad&^@54.183.159.9:27017/?authSource=admin&directConnection=true";
const client = new MongoClient(uri);
log4js.levels.INFO.colour = 'white';
// console.log(log4js.levels.INFO.colour);
log4js.configure({
    appenders: {
        out: {
            type: 'stdout', layout: {
                colored: true,
                type: 'pattern',
                pattern: '%[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%l:%C:%M] [%p] %c - %m',
            }
        },
    },
    categories: {
        default: {appenders: ['out'], level: "trace", enableCallStack: true}
    }

});

async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

class PxBypass {
    tag = "v8.9.0"
    ft = "324"

    constructor() {
        this.flag = false
        this.appId = "PXVb73hTEg"
        this.ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        // ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Mobile/15E148 Safari/604.1'

        this.pxUrl = `https://collector-${this.appId}.px-cloud.net/api/v2/collector`
        this.log = log4js.getLogger('px')

        // let env = fs.readFileSync('./env.json', 'utf-8')
        // env = JSON.parse(env);
        // let keys = Object.keys(env)
        // let selectId = keys[randint(0, keys.length - 1)]
        // selectId = 'd3e94c1cb84038031357a52f'
        // this.log.info('select env', selectId)
        // this.env = env[selectId]

        // this.ua = this.env.navigatorparams.useragent

        this.prox = `http://user-uni001-region-us-sessid-${randint(1000, 5000)}-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600`
        // prox = `http://uni00001_custom_zone_US_sid_${randint(67336718, 67336728)}_time_5:q39CEBTs5A@us.foxyip.com:7778`
        // prox = `http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:${randint(10000, 13500)}`
        this.tlsUrl = 'http://52.52.23.116/tls/forward'

        this.prox = 'http://127.0.0.1:8890'
        this.tlsUrl = 'http://127.0.0.1:58000/tls/forward'


        this.pxHeaders = {
            "authority": `collector-${this.appId}.px-cloud.net`,
            "accept": "*/*",
            "accept-language": "en-US,en;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/x-www-form-urlencoded",
            "origin": "https://www.flyfrontier.com",
            "pragma": "no-cache",
            "user-agent": this.ua
        }


        this.url = 'https://www.flyfrontier.com/'
        this.log.level = 'debug'
        this.uuid = '';
        this.ts = '';
        this.cs = ''
        // # PX15454 o111oooo
        this.num1 = 0
        // # PX11701 111o1o
        this.num2 = ''
        // # PX11701 111o1o
        this.str1 = ''
        this.vid = ''
        this.sid = ''
        this.cts = ''

        this.seq = 0
        this.rsc = 1;
        this.cookies = {}


    }

    async initMongo() {
        this.log.info("init mongo 获取环境数据")
        const database = client.db("env");
        const movies = database.collection("env_shape");
        // Query for a movie that has the title 'The Room'
        const query = {
            'env.funcs': {$ne: null},
        };

        // Execute query
        const movie = await movies.aggregate([
            {$match: query},
            {$sample: {size: 1}}
        ])
        let res = await movie.toArray()
        this.env = res[0].env

        this.ua = this.env.navigatorparams.useragent

        this.log.info('ua', this.ua)
        this.log.info(`proxy ${this.prox}`)

    }

    async add_headers(token) {
        // this.prox = `http://user-uni001-region-us-sessid-${randint(1000, 5000)}-sesstime-5-keep-true:q39CEBTs5A5YQXor@pr.roxlabs.cn:4600`
        // this.prox = `http://unfflcc:76cc14-47b8dd-1f8ace-827836-0c740e@usa.rotating.proxyrack.net:${randint(10000, 13500)}`
        let cks = Object.keys(this.cookies).map((v, k) => `${v}=${this.cookies[v]}`).join('; ')
        this.log.info('cookie', cks)
        let headers = {
            "user-agent": this.ua,
            "authority": "www.flyfrontier.com",
            "accept": "application/json, text/plain, */*",
            "accept-language": "en-US",
            "cache-control": "no-cache",
            "content-type": "application/json",
            "ocp-apim-subscription-key": "dc6844776fe84b1c8b68affe7deb7916",
            "origin": "https://www.flyfrontier.com",
            "pragma": "no-cache",
            "referer": "https://www.flyfrontier.com/",
            "x-dtpc": "10$492787436_542h10vNDAFLLHTQHFKVMUIMICENMIBAMBWCDES-0e0",
            'Authorization': 'Bearer ' + token,
            "cookie": cks
        }
        let res = await axios.post('http://ymx-lcc.unififi.com/header/add', JSON.stringify({
            'brush_fromto': 'LAS-BOS',
            'brush_fromdate': '2023-05-26',
            'brush_header': headers,
            'brush_proxy': this.prox,
            'brush_mode': 'shopping',
            'brush_name': 'js0',
            'brush_type': 'cookieNK',
        }));
        this.log.debug(res.data)

    }

    async do_collector(data) {
        try {
            for (let i = 0; i < data.length; i++) {
                let n = data[i];
                n.d['PX11645'] = this.url;
                n.d["PX11379"] = false;
            }
            console.log(JSON.stringify(data))

            // if (typeof data === 'object') {
            //     data = ht(data)
            // }
            // this.log.info(data)
            // let payload = encodePayload(data, this.uuid, this.ts)
            // let pc = genPc(data, `${this.uuid}:${this.tag}:${this.ft}`)
            // let body = {
            //     "appId": this.appId,
            //     "tag": this.tag,
            //     "uuid": this.uuid,
            //     "ft": this.ft,
            //     "seq": this.seq,
            //     "en": "NTA",
            //     "pc": pc,
            //     "rsc": this.rsc,
            //     "payload": payload,
            // }
            // body = this.updateBody(body);


            let body = this.getPayload(data)
            body.push(`seq=${this.seq}`)
            body.push(`rsc=${this.rsc}`)
            let res = await axios.post(this.tlsUrl, JSON.stringify({
                url: this.pxUrl,
                method: "POST",
                // data: qs.stringify(body),
                data: body.join('&'),
                headers: this.pxHeaders,
                allow_redirects: true,
                debug: true,
                proxy: this.prox,
                id: (new Date().getTime()) + '',
                random_tls: true,
            }), {
                timeout: 5000,
            });
            let inRes = JSON.parse(res.data.text)
            this.log.info(inRes)
            this.parseRes(inRes)
        } catch (err) {
            console.error(err.data);
            throw err;
        }

    };


    updateBody(body) {
        if (this.vid !== "") {
            body.vid = this.vid
        }
        if (this.cs !== "") {
            body.cs = this.cs
        }
        if (this.cts !== "") {
            body.cts = this.cts
        }
        if (this.sid !== "") {
            body.sid = this.sid
        }
        return body
    }

    getPayload(data) {

        let vh = null;
        // console.log('now', le(), JSON.stringify(t))

        // console.log('now', JSON.stringify(data))
        // var A = $u();
        let uuid = this.uuid
        var pc = se(ht(data), function (t, e) {
            return [uuid, t, e]['join'](":");
        }(this.tag, this.ft));
        var b = {
            "vid": this.vid,
            "tag": this.tag,
            "appID": this.appId,
            "cu": this.uuid,
            "cs": this.cs,
            "pc": pc
        };
        var w = bl(data, b, this.ts);
        // console.log("ts", fl())
        // console.log('res', w)
        var E = ["payload=" + w, "appId=" + this.appId, "tag=" + this.tag, "uuid=" + this.uuid, "ft=" + this.ft, "en=" + "NTA"];
        var T = null;
        T && E["push"]('xuuid=' + T);
        this.cs && E["push"]('cs=' + this.cs);
        pc && E["push"]('pc=' + pc);
        var O = this.sid;
        var U = Ol(this.ts);
        (O || U) && E["push"]('sid=' + (O || this.sid) + U);
        var I = [];
        this.vid && E["push"]('vid=' + this.vid);
        // mu && E["push"]('jcs=' + mu);
        var S = this.ci;
        S && E["push"]('ci=' + S);
        // Ru || (Ru = Df(cu));
        var C = this.pxhd;
        C && E["push"]('pxhd=' + C);
        let Qf = this.cts;
        Qf && E["push"]('cts=' + Qf);
        I["length"] >= 0 && E["push"]["apply"](E, I);
        return E;
    }

    parseRes(inRes) {
        let result = void 0;
        if (inRes['ob']) {
            let cks = ie(atob(inRes.ob), this.version()).split('~~~~')
            this.log.info(cks.length, JSON.stringify(cks, null, '\t'))
            for (var ck of cks) {
                let tmp = ck.split('|');

                if (tmp[0] === 'o11o1ooo') {
                    this.log.fatal('result', tmp[1] === '0')
                    result = tmp[1] === '0'
                }
                if (tmp[0] === 'o111oo11') {
                    this.ts = tmp[1]

                }
                if (tmp[0] === '11oo1o') {
                    this.ci = tmp[2]
                    this.token = tmp[4].split('_')[0]
                    this.token2 = tmp[4].split('_')[1]
                }
                if (tmp[0] === 'o1oo11') {
                    this.hash = tmp[2]
                    this.hash2 = tmp[3]
                    this.hashv = tmp[4]
                }

                if (tmp[0] === 'o111oo1o') {
                    this.num1 = tmp[1]

                }
                if (tmp[0] === '1o111o') {
                    this.num2 = tmp[1]
                }

                if (tmp[0] === '11o1o1') {
                    this.str1 = tmp[1]

                }
                if (tmp[0] === 'ooo11o') {
                    this.vid = tmp[1]
                    this.cookies['_pxvid'] = this.vid
                }


                if (tmp[0] === 'oo1111') {
                    this.sid = tmp[1]
                }

                if (tmp[0] === '1ooo11') {
                    this.cs = tmp[1]
                }

                if (tmp[0] === 'o11o111o') {
                    this.cts = tmp[1]
                    this.cookies['pxcts'] = this.cts
                }


                if (tmp.includes('zpxde')) {
                    this.cookies['pxde'] = tmp[3]
                }
                if (tmp.includes('_px2')) {
                    this.cookies['_px2'] = tmp[3]
                    this.log.debug(`px2_decode ${atob(this.cookies['_px2'])}`)
                }
                if (tmp[1] === 'score') {
                    if (tmp[2] === '0') {
                        this.flag = true
                    } else {
                        this.flag = false;
                    }
                }

            }
        }

        if (result) {
            this.result = result;
        }
    }

    version() {
        return parseInt(this.tag.substring(1).replaceAll('.', '')) % 128
    }

    async step1() {

        // this.log.info('setp1')
        let t1 = new Date().getTime();
        this.startTs = t1
        let t2 = t1 + randint(5, 30)
        this.startTs2 = t2
        this.performanceNow = randint(3000, 5000)
        this.px12280 = this.startTs2 + this.performanceNow

        this.uuid = genUuid()
        let data = [{
            "t": "PX12095",
            "d": {
                "PX11645": this.url, "PX12207": 1, "PX12458": this.env.navigatorparams.platform, "PX11902": 0,
                "PX11560": randint(1600, 2600), "PX12248": 3600, "PX11385": t1, "PX12280": t2,
                "PX11496": this.uuid, "PX12564": null, "PX12565": -1,
                "PX11379": false
            }
        }]
        let res = await this.do_collector(data)
        this.seq++;

        this.pxenv = new PxEnv(this.env, this.url, this.sid, this.vid, this.ts, this.num1, this.num2,
            this.str1, this.uuid,
            this.startTs, this.startTs2, this.performanceNow, this.px12280)
            this.pxenv.PX12271 = '10207b2f'
    }

    async step2() {
        this.performanceNow += randint(1000, 2000)

        let data = [{"t": "PX12167", "d": {"PX11648": true}}]
        let res = await this.do_collector(data)

    }

    async step3() {
        this.performanceNow = randint(3000, 4000)
        // let data = genPayload2(this.url, this.sid, this.vid, this.ts, this.num1, this.num2,
        //     this.str1, this.uuid,
        //     this.startTs, this.startTs2, this.performanceNow, this.px12280)
        let data = [this.pxenv.get_px11590()]
        let res = await this.do_collector(data)

    }

    async step4() {
        this.performanceNow += randint(1000, 2000)
        // let data = genPayload4(this.url, this.sid, this.vid, this.ts, this.num1, this.num2,
        //     this.str1, this.uuid,
        //     this.startTs, this.startTs2, this.performanceNow, this.px12280)
        this.pxenv.performanceNow = this.performanceNow
        let data = [
            // this.pxenv.get_px12123(),
            // this.pxenv.get_px11891(),
            this.pxenv.get_px11547()]
        let res = await this.do_collector(data)
    }

async test() {
        // this.prox = 'http://127.0.0.1:8890'
        // this.tlsUrl = 'http://127.0.0.1:58000/tls/forwardios'

        let cks = Object.keys(this.cookies).map((v, k) => `${v}=${this.cookies[v]}`).join('; ')
        this.log.info('cookie', cks)
        let res = await axios.post(this.tlsUrl, JSON.stringify({
            url: 'https://booking.flyfrontier.com/Flight/InternalSelect?o1=BNA&d1=ATL&dd1=Apr%2027,%202024&ADT=1&mon=true&promo=',
            headers: {
    "Host": "booking.flyfrontier.com",
    "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"macOS\"",
    "upgrade-insecure-requests": "1",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "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",
    "sec-fetch-site": "same-site",
    "sec-fetch-mode": "navigate",
    "sec-fetch-user": "?1",
    "sec-fetch-dest": "document",
    "accept-language": "en",
                "cookie": cks
            },
            allow_redirects: true,
            debug: true,
            method: "GET",
            proxy: this.prox,
            random_tls: true,

        }));
        if (res.data.status_code === 200) {
            // console.log(res.data.text)
            this.log.warn('success', res.data.status_code, res.data.text.includes('FlightData'))
            await this.add_headers()
        } else {
            this.log.error('error', res.data.status_code)
        }
    }
    check() {
        if (this.cookies['_px2']) {
            let px2 = this.cookies['_px2'];
            let px2Decode = JSON.parse(atob(px2));

            if (px2Decode.t.toString().startsWith('62') && px2Decode.t.toString().endsWith('04')) {
                return true
            }
        }
        return false

    }
}

async function run() {
    while (true) {
        try {
            // let res = await axios.get('http://ymx-lcc.unififi.com/header/task/pull/cookieF9?brush_name=test')
            // let data = res.data;

            let data = {
                status: 0
            }
            console.log(data)
            // if r.json()['status'] != 0:
            //     #         logger.debug(f'不需要刷值')
            //     #         time.sleep(10)
            //     #         continue
            if (data.status === 0) {
                for (let i = 0; i < 10; i++) {

                    try {
                        let px = new PxBypass()
                        await px.initMongo()
                        await px.step1()
                        // await px.test()
                        // await px.step2()
                        // await sleep(1500)
                        await px.step3()


                        await sleep(1000)
                        await px.step4()
                        await px.test()

                        // await sleep(1500)
                        // await px.add_headers()
                        await sleep(1000)
                    } catch (e) {
                        console.log(e.toString())
                    } finally {
                        await sleep(1000)
                    }


                }

            }
            await sleep(1000)
        } catch (e) {
            console.log(e)
        } finally {
        }
    }


    // }

}


run();
