package pf.shapeFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.net.MalformedURLException;

import org.geotools.data.FeatureWriter;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.Transaction;
import org.geotools.feature.FeatureCollection;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

public class ShapeFl {
	private static final String ERR_FILE_NAME = "Error in shape-file-name: ";
	private static final String ERR_FILE_ACCESS = "Error accessing file: ";
	private static final String ERR_FILE_URL = "Error generating file URL for: ";
	private static final String ERR_FILE_OPEN = "Error opening file: ";
	private static final String ERR_FILE_CLOSE = "Error closing file: ";
	private static final String ERR_WRITE_FEATURES = "Error writing features to shape file";

	private static FeatureWriter<SimpleFeatureType, SimpleFeature> writer;

	public static void open(String fn, SimpleFeatureType featureType)
			throws ShapeFlException {
		try {
			URL fnURL = new File(fn).toURI().toURL();
			ShapefileDataStore shpFl = new ShapefileDataStore(fnURL, true);
			shpFl.createSchema(featureType);
			String typeName = shpFl.getTypeNames()[0];
			writer = shpFl.getFeatureWriter(typeName, Transaction.AUTO_COMMIT);
		} catch (NullPointerException e) {
			throw new ShapeFlException(ERR_FILE_NAME + fn, e);
		} catch (SecurityException e) {
			throw new ShapeFlException(ERR_FILE_ACCESS + fn, e);
		} catch (IllegalArgumentException e) {
			throw new ShapeFlException(ERR_FILE_URL + fn, e);
		} catch (MalformedURLException e) {
			throw new ShapeFlException(ERR_FILE_URL + fn, e);
		} catch (IOException e) {
			throw new ShapeFlException(ERR_FILE_OPEN + fn, e);
		}
	}

	public static void write(
			FeatureCollection<SimpleFeatureType, SimpleFeature> features)
			throws ShapeFlException {
		try {
			Iterator<SimpleFeature> iterator = features.iterator();
			while (iterator.hasNext()) {
				SimpleFeature next = (SimpleFeature) iterator.next();
				SimpleFeature out = (SimpleFeature) writer.next();
				out.setAttributes(next.getAttributes());
				writer.write();
			}
		} catch (IOException e) {
			throw new ShapeFlException(ERR_WRITE_FEATURES, e);
		}
	}

	public static void close() throws ShapeFlException {
		try {
			writer.close();
		} catch (IOException e) {
			throw new ShapeFlException(ERR_FILE_CLOSE, e);
		}
	}

}
