package dynamic.people.dblist;

import dynamic.common.MyAuthenticator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.URL;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: John
 * Date: 26/04/12
 * Time: 10:06
 * To change this template use File | Settings | File Templates.
 */
public class StudentList extends ArrayList<StudentListEntry>{

    private static String STUDENTS_URL = "https://teachdb.doc.ic.ac.uk/db/report?name=Tab+Separated&num=2";

    static StudentList students = null;

    static {
        students = new StudentList(STUDENTS_URL);
    }

    public static StudentList getStudentSubList(String degree, String letterYr){
        ArrayList<String> degrees = StaffList.convertToArrayList(degree);
        ArrayList<String> letterYrs = StaffList.convertToArrayList(letterYr);
        return students.getSubList(degrees,letterYrs);
    }

    private StudentList getSubList(ArrayList<String> categories, ArrayList<String> appointments) {
        StudentList pl = new StudentList();
        for (StudentListEntry entry : this) {
            if(entry.matches(categories,appointments))
                pl.add(entry);
        }
        return pl;
    }

    private StudentList() {}

    private StudentList(String address) {

        try {
            Authenticator.setDefault(new MyAuthenticator());
            URL url = new URL(address);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            in.readLine(); // ignore headers
            String inputLine;
            while ((inputLine = in.readLine()) != null){
                add(new StudentListEntry(inputLine));
            }
            in.close();
        } catch (IOException e) {
            System.err.println("error accessing page - " + address);
            System.exit(0);
        }
    }

}
