/* The class contains a 'execProject' method that projects columns from a table.
 * The method accepts an array of strings that contain the column names to project 
 * and the table on which to perform the projection. A new table is generated and
 * returned which conatins the projected information from the inputs to the method.
 * When projecting columns, the time (start and end) components are automatically
 * projected.
 */

import java.util.*;
import java.lang.*;

class Project 
{
	public static Table execProject(Table S, String[] names)
	{
		Table R = new Table();

		/* Determine which columns can be projected */
		ArrayList projNames = new ArrayList();
		for (int i=0; i<names.length; i++)
		{
			int val = S.col.getColPos(names[i]);
			if (val!=99)
				projNames.add(names[i]);
			else
				CatchErr.columnErr(names[i], "PROJECT");
			
		}

		if ( projNames.size()!=0 ) // more than one column can be projected
		{
			/* convert the columns that can be project held as Object type into String type */
			String[] projCols = new String[projNames.size()];
			for (int i=0; i<projNames.size(); i++)
			{
				projCols[i]=(String)projNames.get(i);
			}

			/* holds the column positions of the column names being projected */
			int[] namePos = new int[projCols.length];
			/* holds the column types of the column names being projected */
			int[] types = new int[projCols.length];

			/* extract all the positions of the columns being projected */ 
			for (int i=0; i<projCols.length; i++)
			{
				namePos[i]=S.col.getColPos(projCols[i]);
			}
			
			/* extract all the types of the columns being projected */ 
			for (int i=0; i<projCols.length; i++)
			{
				types[i]=S.col.getPosType(namePos[i]);
			}

			R.putCol(projCols.length, projCols, types);

			for (int i=0; i<S.getNoRowSet(); i++) /* go through each row */
			{
				Row Si = (Row)S.getRow(i);
				Object[] values = new Object[projCols.length];

				/* extract the column objects in row listed for projection */
				for (int j=0; j<projCols.length; j++)
				{
					
					values[j]=Si.getRowVal(namePos[j]);
				}
				
				/* add the projected row to the output table including the 
				 * automatic projection of the row's time values.
				 */
				R.putRow(values, Si.getRow_st(), Si.getRow_et());
			
			}
		}
		else // found no columns that can be projected (given by user)
		{
			System.out.println("ERROR in PROJECT: No columns given can be projected");
			System.out.println("ASSUMPTION MADE: All columns projected");
			R=S;
		}

		boolean coalFlag=UserInterface.getCoal();
		if (coalFlag)
		{
			AuxFuncs.coalesce(R);
		}
		
		return R;
	}

}
