#include "Behaviors/StateMachine.h"

$nodeclass EggsNearLine : VisualRoutinesStateNode {

	$nodeclass FindEggsAndLine : MapBuilderNode : doStart {
		mapreq.addObjectColor(ellipseDataType, "blue");
		mapreq.addObjectColor(ellipseDataType, "green");
		mapreq.addOccluderColor(lineDataType, "blue");
		mapreq.addOccluderColor(lineDataType, "green");
		mapreq.addObjectColor(lineDataType, "red");
	}

	$nodeclass ReportEggs : VisualRoutinesStateNode : doStart {
		// Get the dividing line (defined as the biggest red line found)
		NEW_SHAPEVEC(line_shapes, LineData, select_type<LineData>(camShS));
		
		NEW_SHAPE(dividingLine, LineData, max_element(line_shapes, 
																							 		LineData::LengthLessThan()));
		if (dividingLine.isValid()) {
      dividingLine->setInfinite(true);
		}
		// Get all of the ellipses
		NEW_SHAPEVEC(ellipse_shapes, EllipseData,
			select_type<EllipseData>(camShS));
		// Counters for eggs that are left or right of the line
		int right = 0;
		int left = 0;
		// If there is no dividing line, report that
		if (!dividingLine.isValid()) {
			cout << "There is no line dividing the ellipses" << endl;
		}
		// Otherwise, count the eggs on each side
		else {
			SHAPEVEC_ITERATE(ellipse_shapes, EllipseData, myellipse)
				// Ellipses that are smaller than 25x25 are considered noise
				if (myellipse->getSemimajor() > 25 && myellipse->getSemiminor() > 25)
				{
					if (dividingLine->pointIsLeftOf(myellipse->getCentroid())) {
						left++;
					} else if (dividingLine->pointIsRightOf(myellipse->getCentroid())) {
						right++;
					}
				}

				else {
					camShS.deleteShape(myellipse);
				}
			END_ITERATE;

			cout << right << " eggs are to the right of the line." << endl;
			cout << left << " eggs are to the left of the line." << endl;
		}

		if ( ellipse_shapes.size() > 0 ) {
			NEW_SKETCH(ellipse0, bool, ellipse_shapes[0]->getRendering());
		}

		if ( dividingLine.isValid() ) {
			NEW_SKETCH(line0, bool, dividingLine->getRendering());
		}
	}

	$setupmachine {
		FindEggsAndLine =C=> ReportEggs
	}
}

REGISTER_BEHAVIOR(EggsNearLine);
