console.log('bundle2!')

printable = (platform) => {
    return platform === "WEB";
}

request = async (method, url, data = null, headers = {}, platform) => {
    if (platform === "WEB") {
        url = url.replace("https://cn.pornhub.com/", "http://127.0.0.1:81/");
    }
    console.log(`request url:${url}`)
    console.log(`request data:${data}`)
    console.log(`request method:${method}`)
    console.log(`request headers:${JSON.stringify((headers))}`)
    if (platform === "WEB") {
        const res = await fetch(url, {
            'mode': 'cors',
            'method': method,
            'headers': headers,
            'body': data
        })
        const resData = await res.text()
        return Promise.resolve({
            'data': resData,
            'headers': res.headers
        });
    }
    return new Promise((resolve, reject) => {
        AF.request(url, method, data, headers, (data, headers, err) => {
            if (err) {
                reject(err);
            } else {
                console.log(`response headers: ${headers}`);
                resolve({
                    'data': data,
                    'headers': JSON.parse(headers)
                });
            }
        });
    })
}


detail = async (url, platform) => {
    try {
        const htmlResp = await request('GET', url, null, {}, platform);
        let {data: html, headers: htmlHeaders} = htmlResp;

        let match = html.match(/var flashvars_[^ ]* = ({.*?});/);
        if (!match || !match.length) {
            console.log('can not found JSON: flashVars');
            throw new Error('JSON not found: flashVars');
        }
        const flashVars = JSON.parse(match[1]);
        if (printable(platform)) {
            console.log(flashVars);
        }
        const mediaDefinitions = flashVars['mediaDefinitions'];
        const formats = [];
        for (const item of mediaDefinitions) {
            const format = {
                'videoUrl': item['videoUrl'],
                'format': item["format"],
                "quality": item["quality"],
            }
            formats.push(format);
        }

        const videoDetails = {
            "title": flashVars["video_title"],
            "thumbnail": flashVars["image_url"],
            "videoId": flashVars["link_url"].match(/viewkey=(.*)/)[1]
        }
        const ret = {
            "code": 200,
            "msg": "",
            "data": {
                "videoDetails": videoDetails,
                "streamingData": {
                    "formats": formats
                }
            },
            "id": "DetailViewModel_detail_url"
        }
        console.log(`detail result: ${JSON.stringify(ret)}`);
        return ret;
    } catch (e) {
        const ret = {
            "code": -1,
            "msg": e.toString()
        }
        console.log(`detail result error: ${JSON.stringify(ret)}`);
        console.log(e);
        return ret;
    }
}
