const fs = require("fs");
const {exec} = require("child_process");

const axios = require("axios");
const {v4: uuidv4} = require('uuid');

const DEEPLEARNING_CAPTCHA_HOST = "http://appointment.lpaconsulting.fr:9000"

function delay(delayInMs) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(2);
        }, delayInMs);
    });
}

function randomIntFromInterval(min, max) { // min and max included
    return Math.floor(Math.random() * (max - min + 1) + min)
}

class SlidingCaptchaSolver {
    constructor(device) {
        this.device = device;
    }

    async solve(page, onResult) {
        await this.sliding_captcha(this.device, onResult)
    }

    async take_screen_shot(name, device) {
        // let stdout1 = await exec("adb -s " + device.serial() + " shell screencap -p /sdcard/" + name)
        console.log("take screenshot " + name);
        await device.screenshot({path: name});
        // let stdout1 = await exec("adb -s " + device.serial() + " exec-out screencap -p > " + name)
        await delay(1000);
        // console.log(`stdout: ${stdout1}`);
    }


    async sliding_captcha(device, onResult) {
//    take screenshot
        console.log("take screenshot")
        let blockedFileName = uuidv4();
        let blockedImageFileName = "blocked_" + blockedFileName + ".png"
        await this.take_screen_shot(blockedImageFileName, device)
        //get resolution of screen
        await this.sendRequest(blockedImageFileName, async (detectedPositionList) => {
            console.log("detectedPosition: " + device.model() + ":" + detectedPositionList);
            if (detectedPositionList.length >= 2) {
                // #xiaomi
                let startPosition = detectedPositionList.filter((positionInfo) => {
                    return positionInfo.label === "origin"
                })[0]
                let targetPosition = detectedPositionList.filter((positionInfo) => {
                    return positionInfo.label === "target"
                })[0]
                if (startPosition !== undefined && targetPosition !== undefined) {
                    let y0 = (startPosition.y2 + startPosition.y1) / 2.0;
                    let x0 = (startPosition.x2 + startPosition.x1) / 2.0;
                    let y1 = (targetPosition.y2 + targetPosition.y1) / 2.0;
                    let x1 = (targetPosition.x2 + targetPosition.x1) / 2.0;
                    let width = targetPosition.x2 - targetPosition.x1;
                    let randomTime = randomIntFromInterval(100, 500)
                    let cmd = `adb -s ${device.serial()} shell input swipe ${x0} ${y0} ${x1 + width * 0.5} ${y0} ${1000 + randomTime}`
                    await delay(2000);
                    console.log("cmd is " + cmd);
                    console.log("will slide captcha");
                    await exec(cmd);
                    await delay(5000);
                    onResult(true)
                } else {
                    console.log("startPosition not found for " + device.model())
                    onResult(false)
                }
            } else {
                console.log("startPosition not found for " + device.model())
                onResult(false)
            }
        })

    }

    async sendRequest(fileName, callback) {
        const fileStream = fs.createReadStream(fileName);
        let response = await axios.post(DEEPLEARNING_CAPTCHA_HOST, fileStream, {
            headers: {
                'Content-Type': 'wav',
                'Authorization': 'Bearer 97e36f7e-340e-4c02-b329-9415faee38c3'
            },
            timeout: 30 * 1000
        }).catch(err => {
            console.log(err.code);
            console.log(err.stack);
            console.log(err.message);
            callback([]);
        })
        if (response === undefined) {
            await callback({});
            return
        }
        if (response.status === 200) {
            let result = response.data;
            console.log(result);
            await callback(result);
            // console.log("will delete png file: " + fileName);
            // await fs.unlink(fileName, (err) => {
            //     if (err) throw err;
            //     console.log(fileName + ' was deleted');
            // })
        } else {
            console.log("error");
            await callback([]);
        }
    }
}

module.exports = SlidingCaptchaSolver