#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/StateSetManipulator>

#include <osgDB/ReadFile>
#include <osg/Notify>
#include <osg/ImageStream>
#include <osg/Camera>
#include <osg/BlendFunc>
#include <osg/Material>
#include <osg/Geometry>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/ProxyNode>
#include <osg/TexEnvCombine>
#include <osg/BlendEquation>
#include <osg/PositionAttitudeTransform>
#include <osgUtil/CullVisitor>

class CEventCallback : public osgGA::GUIEventHandler
{
public:

	/** Handle events, return true if handled, false otherwise. */
	virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object* object, osg::NodeVisitor* nv) 
	{
		osgGA::GUIEventAdapter::EventType		e = ea.getEventType();
		osg::Vec2								mouse;

		// Mouse
		mouse.set(ea.getX(), ea.getY());

		{
			if (e == osgGA::GUIEventAdapter::PUSH)
			{
				// Checking intersections
				osgViewer::Viewer									*viewer = static_cast<osgViewer::Viewer*>(&aa);
				osgUtil::LineSegmentIntersector::Intersections		intersections;

				bool result = viewer->computeIntersections(mouse.x(), mouse.y(), intersections);
				OSG_NOTICE << "compute intersections : " << ea.getX() << " " << ea.getY() << " result : " << result << std::endl;

				if (!intersections.empty())
				{
					OSG_NOTICE << "intersections !!" << std::endl;
					for (osgUtil::LineSegmentIntersector::Intersections::const_iterator it = intersections.begin(); it != intersections.end(); ++it)
					{
						if (!it->nodePath.empty())
						{
							OSG_NOTICE << "nodePath" << std::endl;
							for (osg::NodePath::const_iterator pathIt = it->nodePath.begin(); pathIt != it->nodePath.end(); ++pathIt)
							{
							}
						}
					}
				}
			}
		}
		return false;
	}
};


int	main(int ac, char **av)
{
	osg::setNotifyLevel(osg::NOTICE);

	osgDB::Registry::instance()->getDataFilePathList().push_back("../../media/");

	// Viewer init
	osgViewer::Viewer	viewer;

    viewer.addEventHandler(new osgViewer::StatsHandler());
	viewer.setUpViewInWindow(100, 100, 800, 600);

	osg::Group * group = new osg::Group();

	{ //Relative
		osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform();
		pat->setPosition(osg::Vec3(-10,0,0));
		pat->addChild(osgDB::readNodeFile("cow.osg"));
		pat->setReferenceFrame(osg::Transform::RELATIVE_RF);
		group->addChild(pat);
	}

	{ //Absolute
		osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform();
		pat->addChild(osgDB::readNodeFile("cow.osg"));
		//pat->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
		pat->setReferenceFrame(osg::Transform::RELATIVE_RF);
		pat->setPosition(osg::Vec3(10,0,0));
		group->addChild(pat);
	}

	group->setEventCallback(new CEventCallback());
	viewer.setSceneData(group);
	viewer.getCamera()->setCullingMode(osg::CullSettings::CullingModeValues::NO_CULLING);

	viewer.run();

	return (0);
}
