const axios = require("axios");
const CAPCHA_NOT_READY = "CAPCHA_NOT_READY";
const TWO_CAPTCHA_CONNECTION_FAILED = "TWO_CAPTCHA_CONNECTION_FAILED";
const REGEX_DATA_SITE_KEY = "data-sitekey=[\"a-z0-9A-Z]+";
const API_KEY = "d66aaf490d8aa424a5175e1fbd1aadea";
const SITE_KEY = "6LdUViwUAAAAAOBJjtMsmKc9C7200Djd31w2mCs7";

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

class SolveCaptcha {

    constructor(page) {
        this.page = page;
    }

    async start(handle_solution_received) {
        await this.solve_captcha(SITE_KEY, handle_solution_received)
    }

    async solve_captcha(site_key, handle_solution_received) {
        try {
            console.log("solve_captcha(), for " + this.page.url())
            let url_get = `http://2captcha.com/in.php?key=${API_KEY}&method=userrecaptcha&googlekey=${site_key}&pageurl=${this.page.url()}`;
            let res = await axios.get(url_get)
            console.log(`statusCode: ${res.status}`);
            let results = res.data.split("|");
            this.captcha_id = results[1];
            let solution = CAPCHA_NOT_READY;
            let status_code = 1;
            await delay(15 * 1000)
            while (solution === CAPCHA_NOT_READY || status_code !== 200) {
                await this.get_solution(this.captcha_id, (status, sol) => {
                    status_code = status;
                    solution = sol
                })
            }
            handle_solution_received(solution)
        } catch (e) {
            console.log(e)
            handle_solution_received(TWO_CAPTCHA_CONNECTION_FAILED)
        }

    }

    async get_solution(catcha_id, onSolutionFound) {

        console.log("get_solution() called")
        try {
            let url_response = `http://2captcha.com/res.php?key=${API_KEY}&action=get&id=${catcha_id}`;
            let res = await axios.get(url_response)
            console.log(`statusCode: ${res.status}`);
            let results = res.data.split("|");
            let solution
            if (results.length > 1)
                solution = results[1];
            else {
                solution = results[0]
            }
            onSolutionFound(res.status, solution)
            await delay(5 * 1000)
        } catch (e) {
            onSolutionFound(1, CAPCHA_NOT_READY)
            await delay(5 * 1000)
        }

    }
}

module.exports = {SolveCaptcha, TWO_CAPTCHA_CONNECTION_FAILED}