import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

import org.geotools.referencing.CRS;
import org.opengis.referencing.crs.CoordinateReferenceSystem;


public class FullLookups {

    public static void main(String[] args) throws Exception {
        // don't want to see the ton of warnings coming out of referencing logging
        System.err.close();
        
        // the wkt we already encountered
        Set<String> wkts = new HashSet<String>();
        int skipped = 0;
        int success = 0;
        int failed = 0;
        int error = 0;
        
        File root = new File("/tmp/prj");
        for (File f : root.listFiles()) {
            String wkt = readFile(f);
            if(wkts.contains(wkt)) {
                skipped++;
                continue;
            }
            wkts.add(wkt);

            long start = System.currentTimeMillis();
            try {
                CoordinateReferenceSystem crs = CRS.parseWKT(wkt);
                Integer code = CRS.lookupEpsgCode(crs, true);
                if(code == null) {
                    failed++;
                } else {
                    success++;
                }
                System.out.println(f.getName() + " -> " + code);
            } catch(Exception e) {
                System.out.println(f.getName() + " error: " + e.getMessage());
                error++;
            } finally {
                long end = System.currentTimeMillis();
                System.out.println(f.getName() + " lookup took: " + (end - start) / 1000.0);
            }
        }
        System.out.println(skipped + "," + success + ", " + failed + ", " +  error);
    }

    private static String readFile(File f) throws Exception {
        BufferedReader reader =  new BufferedReader(new InputStreamReader(new FileInputStream(f)));
        String line;
        StringBuffer sb = new StringBuffer();
        while((line = reader.readLine()) != null)
            sb.append(line).append("\n");
        reader.close();
        return sb.toString();
    }
}
