package mobvista.dmp.datasource.apptag.crawler;

import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;
import org.apache.http.HttpHost;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Random;

/**
 * author: houying
 * date  : 16-11-4
 * desc  :
 */
public class ProxyManager {
    private List<HttpHost> proxyHosts;
    private Random random = new Random(System.currentTimeMillis());
    private final boolean useProxy;
    public ProxyManager(boolean useProxy) throws IOException {
        this.useProxy = useProxy;
        if (useProxy) {
            List<String> proxyList = CharStreams.readLines(new InputStreamReader(ProxyManager.class.getResourceAsStream("/proxy.conf")));
            proxyHosts = Lists.newArrayList();
            for (String proxy : proxyList) {
                String[] host = proxy.split(":");
                proxyHosts.add(new HttpHost(host[0], Integer.valueOf(host[1])));
            }
        }
    }

    public HttpHost getProxy() {
        return useProxy ? proxyHosts.get(nextRandom()):null;
    }

    public int nextRandom() {
        int n = random.nextInt() % proxyHosts.size();
        return n < 0 ? n + proxyHosts.size():n;
    }

    public static void main(String[] args) throws IOException {
        ProxyManager manager = new ProxyManager(false);
        for (int i = 0; i < 10; i++) {
            System.out.println(manager.nextRandom());
        }
    }

}
