package peca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 
 * @author nori090
 */
public class BuildChannelDataTableThread extends Thread {

    private URL[] urls;
    private ChannelData[] channeldata;
    private static final Object lock = new Object();

    public BuildChannelDataTableThread(URL[] urls) {
        this.urls = urls;
    }

    @Override
    public void run() {
        ArrayList<ChannelData> list = new ArrayList<ChannelData>();
        for (URL url : urls) {
            try {
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) con.getContent(), "UTF-8"));
                String s = null;
                while ((s = br.readLine()) != null) {
                    list.add(new ChannelData(s));
                }
            } catch (IOException ex) {
                Logger.getLogger(BuildChannelDataTableThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        synchronized (lock) {
            ChannelData[] d = list.toArray(new ChannelData[]{});
            channeldata = d;
        }
    }

    public ChannelData[] get() {
        synchronized (lock) {
            return channeldata;

        }
    }

    public static void main(String[] args) {
        try {
            BuildChannelDataTableThread a = new BuildChannelDataTableThread(new URL[]{new URL("http://192.168.24.51:8080/http://kp.podzone.net/index.txt")});
            a.run();
            for (ChannelData d : a.get()) {
                System.out.println(d);
            }
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }
}
