/*****************************************************************
 * PolyLineExample.java
 * Just an example of how to write a Polyline Shapefile with the 
 * NVS Shapefile library, v2.0
 *
 ****************************************************************/

import java.io.*;
import com.nvs.shapefile.*;
import java.util.*;

public class PolylineExample 
{	
	public static void main(String args[])
	{		
		new PolylineExample();
	}
	
	public PolylineExample()
	{
		// Create a new Shapefile of type POLYLINE
		Shapefile shp = new Shapefile(Shapefile.SHAPETYPE_POLYLINE);
		// Add a table description for the name "soil_type". You have to do this
		//  before you add a ShapeObject with a record, else you'll get an exception
		//  because the Shapefile's TableDescription won't match the ShapeObject's
		//  Record
		shp.getTableDescription().addTableDescriptor(new TableDescriptor("soil_type"));
		
		// Create a ShapeObject with an UNDEFINED type. This is handy when you don't
		//  know what type you'll need the ShapeObject to be.
		ShapeObject shpObj = new ShapeObject();
		
		// Create some points and add them to the ShapeObject
		Point p = new Point(1, 2);
		shpObj.addPoint(p);
		p = new Point(2, 3);
		shpObj.addPoint(p);
		p = new Point(4, 3);
		shpObj.addPoint(p);
		
		// Create a new record and add a "soil_type" field to it
		Record rec = new Record();
		rec.addField(new RecordField("soil_type", "sandy"));
		
		// Set the ShapeObject's Record 
		shpObj.setRecord(rec);
		
		// Add the ShapeObject to the Shapefile
		shp.addShapeObject(shpObj);
		
		// Instead of adding points one at a time, we'll add a collection this time
		//  loop through ten times, adding a point to the ArrayList each time
		ArrayList arlPoints = new ArrayList();
		for(int i=0;i<10;i++)
		{
			arlPoints.add(new Point(i, i*2));
		}
		// Create a new ShapeObject, but this time specify the type as POLYLINE
		shpObj = new ShapeObject(ShapeObject.POLYLINE);
		// Set the new ShapeObject's points to the ArrayList
		shpObj.setPoints(arlPoints);
		
		shp.addShapeObject(shpObj);
		
		// Write the shapefile. Handle the IOException that may occur. Note that 
		//  the BoundingBox's for this shapefile and for each shapeobject have been 
		//  calculated as they were added/writen.
		try
		{
			shp.write("PolylineExample");
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
		// For kicks, let's reset the shapefile and set it's shapes to an ArrayList,
		//  but we'll specify one shape that doesn't fit the group. It will
		//  throw an InvalidShapeTypeException:
		shp = new Shapefile(Shapefile.SHAPETYPE_POLYLINE);
		ArrayList arlShapes = new ArrayList();
		for(int i=0;i<20;i++)
		{
			// Make the 11th shape a polygon
			if(i == 10)
			{
				shpObj = new ShapeObject(ShapeObject.POLYGON);
			}
			else
			{
				shpObj = new ShapeObject(ShapeObject.POLYLINE);
			}
			arlShapes.add(shpObj);
		}
		shp.setShapeObjects(arlShapes);
	}
}