package usda.weru.util.gis;

//import gisviewer.shapefile.Swab;
import java.io.DataInputStream;
import java.io.EOFException;
import de.schlichtherle.truezip.file.TFileInputStream;
import java.io.IOException;
import java.util.Vector;

/**
 *
 * @author wjr
 */
public class ReadShapefileHeaders {

    Vector<HoleyPolygon> V_hp = new Vector<HoleyPolygon>();

    /**
     *
     * @param fileName
     */
    public ReadShapefileHeaders(String fileName) {
        DataInputStream in = null;
        int multiPartPolygons = 0;

//        ReadShapefile rsf = new ReadShapefile();
        try {
            if (!fileName.endsWith(".shp")) {
                fileName += ".shp";
            }
            in = new DataInputStream(new TFileInputStream(fileName));
            FileHeader fh = new FileHeader();
            fh.read(in);
            System.out.println(fh);
            while (true) {
                RecordHeader rh = new RecordHeader();
                rh.read(in);
//                System.out.println(rh + " avail " + in.available());
                if (rh.recordType != 5) {
                    in.skipBytes(rh.contentLength - 4);
                } else {
                    HoleyPolygon hp = new HoleyPolygon(in);
//                    System.out.println(hp);
                    if (hp.numParts > 1) {
                        multiPartPolygons++;
                    }
                    V_hp.add(hp);
                }
            }
        } catch (EOFException eofe) {
            System.out.println("done " + multiPartPolygons);
        } catch (IOException e) {
            //System.err.println("RunFileData: " + e);
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        if (args.length == 0) {
            args = new String[1];
            args[0] = "db/wind_gen/WINGEN_20090508/WINGEN_20090508";
//            args[0] = "db/cligen/shapetest/CLIGEN_areas_04_04_08_DD_NAD83";
//            args[0] = "data/CLIGEN4Larry2/CLIGEN_areas_04_04_08_DD_NAD83";
//            args[0] = "data/CLIGEN_areas_04_04_08/CLIGEN_areas_04_04_08";
//            args[0] = "data/CLIGEN_areas_04_04_08/CLIGEN_areas_04_04_08_reprojected.shp";
//            args[0] = "C:/weps.svn/GISViewer/uDig/data-v1_1/cities.shp";
//            args[0] = "C:/weps.svn/GISViewer/uDig/data-v1_1/countries.shp";
        }
        ReadShapefileHeaders rs = new ReadShapefileHeaders(args[0]);
        ReadDBFFile dbf = new ReadDBFFile(args[0]);

        for (int idx = 0; idx < rs.V_hp.size(); idx++) {
            HoleyPolygon hp = rs.V_hp.get(idx);
            String dbfs = dbf.getRecord(idx);
            if (hp.numParts == 1) {
                continue;
            }
            System.out.println(hp + " " + dbfs);
        }
    }
}
