const ProxyVerifier = require('proxy-verifier');
const async = require('async');
const {
    readFileSync,
    appendFileSync
} = require('fs');

const delimiter = "\n";

const IPS = readFileSync('ips.txt', 'utf8');

const logerreur = (ip, err, more = '') => {
    return appendFileSync('../logs/logs-error.txt', `IP: ${ip}: Erreur: ${more}\n${JSON.stringify(err,null,4)}\n`);
};
const logok = (ip, port, msg) => {
	appendFileSync('../results/proxy-ok-raw.txt', `${ip}:${port}\n`);
    return appendFileSync('../logs/logs-ok.txt', `IP: ${ip}: PORT: ${port} OK:\n${JSON.stringify(msg,null,4)}\n`);
};
async.each(IPS.split(delimiter), (proxy, callback) => {
    console.log(proxy);
    proxy = proxy.split(':');
    if (proxy.length === 2) {
        const ip = String(proxy[0]).replace(/ /g, '');
        const port = parseInt(String(proxy[1]).replace(/ /g, ''));
		
        ProxyVerifier.testAll({
            ipAddress: ip,
            port,
            protocol: 'http'
        }, function(error, result) {

            if (error) {
                logerreur(ip, error);
                callback();
            } else {
                let {
                    ok
                } = result.tunnel;
                let protoOk = result.protocols.http.ok;

                if (ok === false || protoOk === false) {
                    logerreur(ip, result, `tunnel: ${(ok) ? 'GOOD' : 'BAD'} / protocol: ${(protoOk) ? 'GOOD' : 'BAD'}`);
                } else if (ok === true && protoOk === true) {
                    logok(ip, port, result);
                } else {
                    logerreur(ip, result);
                }
                callback();
            }
        });
    } else {
        callback();
    }

});