/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <math.h>

#include <QDebug>
#include <QMouseEvent>
#include <QPainter>

#include "MvQPointSelection.h"
#include "MvQPlotView.h"
#include "MgQPlotScene.h"
#include "MgQLayoutItem.h"

MvQPointSelection::MvQPointSelection(MgQPlotScene *scene,MvQPlotView *view,QGraphicsItem *parent) : 
	MvQPlotItem(scene,view,parent)
{	
	pen_=QPen(QColor(0,0,255,230),2);
	pen_.setCosmetic(true);
	brush_=QBrush(QColor(0,0,255,180));
	hoverBrush_=QBrush(QColor(164,219,255,150));

	currentAction_=NoAction;
	zoomLayout_=0;
	point_=QPointF();
	pointDefined_=false;

	//selectionPen_=QPen(QColor(0,0,0),2);
	//selectionPen_.setCosmetic(true);

	selectorSize_=32.;
	physicalSelectorSize_=32.;
	hover_=false;
}

MvQPointSelection::~MvQPointSelection()
{
}

QRectF MvQPointSelection::boundingRect() const
{
	checkSelectorSize();	
	float d=selectorSize_/2.;
	return QRectF(point_.x()-d,point_.y()-d,d*2.,d*2.);
}

void MvQPointSelection::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
	if(!pointDefined_)
	  	return;
  
  	checkSelectorSize();

	painter->setRenderHint(QPainter::Antialiasing);	

	QBrush brush;
		
	//Hover
	if(hover_)
	{
		brush=hoverBrush_; 	  
	}
	else
	{
	  	brush=brush_;
	}	
	
	painter->setPen(pen_);
	painter->setBrush(brush);

	float d=selectorSize_/2.-1.;	
	float x=point_.x();
	float y=point_.y();
		
	QRectF rIn=QRectF(x-d/4.,y-d/4.,d/2.,d/2.);
	QRectF rOut=QRectF(x-d,y-d,d*2.,d*2.);
	
	painter->drawEllipse(rIn);
	
	painter->setBrush(QBrush());
	painter->drawEllipse(rOut);
	//painter->drawLine(x-d,y,x+d,y);
	//painter->drawLine(x,y-d,x,y+d);
}

void MvQPointSelection::mousePressEventFromView(QMouseEvent *event)
{
	checkSelectorSize();
	
	if(!activated_ || !acceptMouseEvents_)
		return;

	hover_=false;

	if(!pointDefined_)
	{
		//Get item position
		QPointF p = mapFromScene(plotView_->mapToScene(event->pos()));
		
		if((zoomLayout_=plotScene_->findProjectorItem(mapToScene(p))) == 0) 
		{
			currentAction_=NoAction;
		}
		else
		{
			currentAction_=NoAction;
		
			point_=p;
			pointDefined_=true;
			setVisible(true);
			
			QPointF gp, sp=point_;
			zoomLayout_->mapFromSceneToGeoCoords(mapToScene(sp),gp);
						
			zoomLayout_=0;
			coordPoint_=gp;
			
			emit pointIsDefined(gp.y(),gp.x());
		}
	}

	else
	{
		
		dragPos_=mapFromScene(plotView_->mapToScene(event->pos()));
	
		//Checks if the drag point is		
		//in the selection rentangle and starts a move action 					
		if((zoomLayout_=plotScene_->firstProjectorItem()) != 0 &&
		    checkPointInSelector(dragPos_) == true)
		{
			
		  	currentAction_=MoveAction;
			QPointF xp=dragPos_-point_;

			qDebug() << "xp" << dragPos_<< xp;
												
			currentAction_=MoveAction;
			setCursor(QCursor(Qt::SizeAllCursor));			
		}
		else
		{
			currentAction_=NoAction;
			dragPos_=QPointF();	
		}
	}
}

void MvQPointSelection::mouseMoveEventFromView(QMouseEvent *event)
{
	if(!activated_ || !acceptMouseEvents_)
		return;

	QPointF pos = mapFromScene(plotView_->mapToScene(event->pos()));

	if(currentAction_ == MoveAction)
	{	
		QPointF p = point_ + (pos - dragPos_);				
		checkPoint(p);
		point_=p; 
	
		prepareGeometryChange();

		dragPos_=pos;
		update();		
	}
	else if(event->buttons() ==  Qt::NoButton)
	{		
		bool oriHover=hover_;
		hover_=false;
		
		if(checkPointInSelector(pos))
		{
			hover_=true;
		}	

		if(hover_ != oriHover)
		{
			update();
		}
	}
}

 void MvQPointSelection::mouseReleaseEventFromView(QMouseEvent *event)
 {
	if(!activated_ || !acceptMouseEvents_)
		return;

	QPointF pos = mapFromScene(plotView_->mapToScene(event->pos()));

	if(currentAction_ == MoveAction)
	{
		QPointF p = point_ + (pos - dragPos_);				
		checkPoint(p);
		point_=p; 
		
		prepareGeometryChange();
		
		QPointF sp=point_;
		QPointF gp;
		zoomLayout_->mapFromSceneToGeoCoords(mapToScene(sp),gp);
		
		currentAction_=NoAction;
		zoomLayout_=0;
		dragPos_=QPointF();
		coordPoint_ =gp;

		emit pointIsDefined(gp.y(),gp.x());

		update();	
		unsetCursor();
	}
 }


void MvQPointSelection::setPoint(double lat,double lon)
{
	//double west, double north, double east, double south)
	
	double x=lon;
	double y=lat;
		
	QPointF sp;

	if(!pointDefined_)
	{
		if((zoomLayout_=plotScene_->firstProjectorItem()) == 0)
		{
			return;
		}
	}
	else
	{
		sp=point_;
		if((zoomLayout_=plotScene_->findProjectorItem(mapToScene(sp))) == 0)
		{
			return;

		}
	}

	
	QPointF gp(x,y);

	qDebug() << zoomLayout_->containsGeoCoords(gp);

	if(zoomLayout_->containsGeoCoords(gp))
	{
		zoomLayout_->mapFromGeoToSceneCoords(gp,sp);	
		
		sp=mapFromScene(sp);
	
		prepareGeometryChange();
		point_=sp;
		coordPoint_=gp;
		pointDefined_=true;
		update();
	}
	else
	{
		pointDefined_=true;
		QPointF sp=point_;

		sp=mapToScene(sp);
		
		QPointF gp;
		zoomLayout_->mapFromSceneToGeoCoords(sp,gp);
		
		emit pointIsDefined(gp.y(),gp.x());
	}
}
	
void MvQPointSelection::clearPoint()
{
	currentAction_=NoAction;
	prepareGeometryChange();
	point_=QPointF();
	pointDefined_=false;
	coordPoint_=point_;
	hover_=false;
	update();
	emit pointIsUndefined();
}


// It should be called only after zoom!!!
// If the projection is changed the line should be set "undefined"!!

void MvQPointSelection::reset()
{
	if(!pointDefined_)
		return;

	//We need to find the projectorItem!!
	QPointF sp;

	if((zoomLayout_=plotScene_->firstProjectorItem()) == 0)
	{
		clearPoint();
		return;
	}

	
	QPointF gp=coordPoint_;

	//qDebug() << coordPoint_;

	if(zoomLayout_->containsGeoCoords(gp))
	{
		zoomLayout_->mapFromGeoToSceneCoords(gp,sp);	
		sp=mapFromScene(sp);
	
		prepareGeometryChange();
		point_=sp;
		coordPoint_=gp;
		pointDefined_=true;
		update();
	}
	else
	{
		clearPoint();
	}
}

void MvQPointSelection::setActivated(bool b)
{
	activated_=b;
}


bool MvQPointSelection::checkPointInSelector(QPointF &p)
{
  	float d=selectorSize_/2.;
	QRectF r(point_.x()-d,point_.y()-d,d*2.,d*2.);
		
	return r.contains(p);
}


void MvQPointSelection::checkPoint(QPointF &p)
{
	if(!zoomLayout_)
	{
		p=QPointF();
	}

	//Plot area in scene coordinates
	QRectF plotRect=mapRectFromScene(zoomLayout_->mapToScene(zoomLayout_->boundingRect()).boundingRect());

	if(p.x() > plotRect.right())
	{
		p.setX(plotRect.right());
	}
	else if(p.x() < plotRect.left())
	{
		p.setX(plotRect.left());
	}
	if(p.y() > plotRect.bottom())
	{
		p.setY( plotRect.bottom());
	}
	else if(p.y() < plotRect.top())
	{
		p.setY(plotRect.top());
	}	

}

void MvQPointSelection::checkSelectorSize() const
{  
	selectorSize_=physicalSelectorSize_/parentItem()->scale();	
}