package dynamic.people.dblist;

import dynamic.common.CommonConfig;
import dynamic.common.MyAuthenticator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.Authenticator;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;

/**
 * Created with IntelliJ IDEA.
 * User: John
 * Date: 26/04/12
 * Time: 10:06
 * To change this template use File | Settings | File Templates.
 */
public class StaffList extends ArrayList<StaffListEntry>{

    static StaffList doc_staff = new StaffList(CommonConfig.getDatabaseURL() + "/report?name=Tab+Separated&num=0");

    public static StaffList getAllDocStaff() {
        return doc_staff;
    }

    public static StaffList getDocStaffSubList(String category, String appointment){
        ArrayList<String> categories = convertToArrayList(category);
        ArrayList<String> appointments = convertToArrayList(appointment);
        return doc_staff.getSubList(categories,appointments);
    }

    static ArrayList<String> convertToArrayList(String s) {
        ArrayList<String> al = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(s,",");
        while(st.hasMoreTokens())
            al.add(st.nextToken());
        return al;
    }

    private StaffList getSubList(ArrayList<String> categories, ArrayList<String> appointments) {
        StaffList pl = new StaffList();
        for (StaffListEntry entry : this) {
            if(entry.matches(categories,appointments))
                pl.add(entry);
        }
        return pl;
    }

    private StaffList() {}

    private StaffList(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 StaffListEntry(inputLine));
            }
            in.close();
        } catch (IOException e) {
            System.err.println("error accessing page - " + address);
            System.exit(0);
        }

    }

    public HashSet<String> getAllValues(String field) {
        HashSet<String> res = null;
        try {
            Field f = StaffListEntry.class.getDeclaredField(field);
            res = new HashSet<String>();
            for (StaffListEntry staffListEntry : this) {
                String v = (String) f.get(staffListEntry);
                if(!res.contains(v))res.add(v);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return res;
    }
}
