package org.coderepos.nori090.peercast;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.io.IOUtils;

public class IndexTxtUtil {
    private IndexTxtUtil() {
    };

    static ConcurrentHashMap<String, List<String>> cache = new ConcurrentHashMap<String, List<String>>();

    static long thread_count = 0;

    public static List<String> getIndexTxtAtProxy( final String str_url ) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                URL url;
                HttpURLConnection con = null;
                BufferedReader br = null;
                try {
                    url = new URL( "http://localhost:8080/" + str_url );
                    con = (HttpURLConnection) url.openConnection();
                    br = new BufferedReader( new InputStreamReader( con.getInputStream(), "UTF-8" ) );
                    String s = null;
                    ArrayList<String> list = new ArrayList<String>();
                    while ( ( s = br.readLine() ) != null ) {
                        list.add( s );
                    }
                    cache.put( str_url, list );
                }
                catch ( Exception e ) {
                    e.printStackTrace();
                }
                finally {
                    if ( con != null ) {
                        con.disconnect();
                    }
                    IOUtils.closeQuietly( br );
                }
            }
        };
        thread_count++;
        new Thread( runnable, "PeerCastChecker$getIndexTxtAtProxy" + thread_count ).start();
        return cache.get( str_url );
    }

}
