/***************************** 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 "MvQRangeWidget.h"

#include <QCursor>
#include <QDebug>
#include <QHBoxLayout>
#include <QLabel>
#include <QMouseEvent>
#include <QPainter>
#include <QPushButton>
#include <QSpinBox>
#include <QVBoxLayout>

MvQRangeWidget::MvQRangeWidget(QWidget *parent) : 
   QWidget(parent),
   rangeStartIndex_(-1),
   rangeEndIndex_(-1),
   ignoreSpinChange_(false)
{	
	QVBoxLayout *layout=new QVBoxLayout(this);
	
	QPushButton *allPb=new QPushButton(tr("Whole range"),this);
	layout->addWidget(allPb);
	
	connect(allPb,SIGNAL(clicked(bool)),
		this,SLOT(slotSelectWholeRange(bool)));
	
	
	QHBoxLayout* minHb=new QHBoxLayout;
	layout->addLayout(minHb);
	
	QLabel *label=new QLabel(tr("Top:"));
	minHb->addWidget(label);
	startSpin_=new QSpinBox(this);
	minHb->addWidget(startSpin_);
	
	plot_=new MvQRangePlotWidget(this);
	layout->addWidget(plot_,1);
		
	QHBoxLayout* maxHb=new QHBoxLayout;
	layout->addLayout(maxHb);
	
	label=new QLabel(tr("Bottom:"));
	maxHb->addWidget(label);
	endSpin_=new QSpinBox(this);
	maxHb->addWidget(endSpin_);
		
	connect(startSpin_,SIGNAL(valueChanged(int)),
		this,SLOT(slotStartSpin(int)));
		
	connect(endSpin_,SIGNAL(valueChanged(int)),
		this,SLOT(slotEndSpin(int)));
}

void MvQRangeWidget::setRange(int start, int end)
{
	rangeStartIndex_=start;
	rangeEndIndex_=end; 
	
	if(values_.count() >0)
	{
		if(rangeEndIndex_ >values_.count()-1)
		   rangeEndIndex_=values_.count()-1;	
		
		updateSpins();
		plot_->update();
	}
	
	emit valueChanged(rangeStartIndex_,rangeEndIndex_);		
}  

void MvQRangeWidget::reset(QVector<float> d)
{
  	if(values_.count() == d.count())
	{
	  	return; //!!!
	}	

  	values_=d;
	if(rangeStartIndex_==-1)
	{
		rangeStartIndex_=0;
		rangeEndIndex_=values_.count()-1;
	}	
	else
	{
	  	if(rangeStartIndex_ > values_.count()-1)
		   rangeStartIndex_=0;
		if(rangeEndIndex_ >values_.count()-1)
		   rangeEndIndex_=values_.count()-1;	
	}
	
	
	ignoreSpinChange_=true;
	startSpin_->setRange(1,values_.count());
	endSpin_->setRange(1,values_.count());	
	ignoreSpinChange_=false;
	
	updateSpins();
	
	plot_->update();
	
	emit valueChanged(rangeStartIndex_,rangeEndIndex_);	
}

float MvQRangeWidget::startValue()
{
  	return (values_.count() >0)?values_.at(0):0.;
}	

float MvQRangeWidget::endValue()
{
  	return (values_.count() >0)?values_.at(values_.count()-1):0.;
}	

float MvQRangeWidget::value(int i)
{
  	return (i >=0 && i < values_.count())?values_.at(i):0.;
}	

void MvQRangeWidget::adjustRange(int startV,int endV,float deltaPercent)
{
	if(values_.count() < 2)
		return;
			
	int delta=deltaPercent*static_cast<float>(values_.count()-1);
	if(startV+delta < 0 || endV+delta > values_.count()-1)
		return;
	else
	{  	  
		rangeStartIndex_=startV+delta;
		rangeEndIndex_=endV+delta;
		updateSpins();
		emit valueChanged(rangeStartIndex_,rangeEndIndex_);
	}	
}  

void MvQRangeWidget::adjustRangeStart(int startV,float deltaPercent)
{
	if(values_.count() < 2)
		return;
			
	int delta=deltaPercent*static_cast<float>(values_.count()-1);
	if(startV+delta < 0 || startV+delta > rangeEndIndex_-5)
		return;
	else
	{  	  
		rangeStartIndex_=startV+delta;
		updateSpins();
		emit valueChanged(rangeStartIndex_,rangeEndIndex_);
	}	
}  

void MvQRangeWidget::adjustRangeEnd(int endV,float deltaPercent)
{
	if(values_.count() < 2)
		return;
			
	int delta=deltaPercent*static_cast<float>(values_.count()-1);
	if(endV+delta > values_.count()-1  || endV+delta < rangeStartIndex_+5)
		return;
	else
	{  	  
		rangeEndIndex_=endV+delta;		
		updateSpins();
		emit valueChanged(rangeStartIndex_,rangeEndIndex_);
	}	
}  

float MvQRangeWidget::rangeStartPercent() const	
{
  	if(values_.count() > 2)
	  	return static_cast<float>(rangeStartIndex_)/static_cast<float>(values_.count()-1);
	else
	  	return 0;
}

float MvQRangeWidget::rangeEndPercent() const
{
  	if(values_.count() > 2)
	  	return static_cast<float>(rangeEndIndex_)/static_cast<float>(values_.count()-1);
	else
	  	return 0;
}

float MvQRangeWidget::indexPercent(int index) const
{ 
  	if(values_.count() > 2 && index >= 0 && index <= values_.count())
	  	return static_cast<float>(index)/static_cast<float>(values_.count()-1);
	else
	  	return 0;
}

int MvQRangeWidget::valueCount()
{
  	return values_.count();
}

void MvQRangeWidget::updateSpins()
{
 	ignoreSpinChange_=true;
	startSpin_->setValue(rangeStartIndex_+1);
	endSpin_->setValue(rangeEndIndex_+1);
	ignoreSpinChange_=false;
}  


void MvQRangeWidget::slotStartSpin(int value)
{
	if(ignoreSpinChange_)
	  	return;

	rangeStartIndex_=value-1;
	plot_->update();
	emit valueChanged(rangeStartIndex_,rangeEndIndex_);	
}	

void MvQRangeWidget::slotEndSpin(int value)
{
	if(ignoreSpinChange_)
	  	return;

	rangeEndIndex_=value-1;
	plot_->update();
	emit valueChanged(rangeStartIndex_,rangeEndIndex_);	
}

void MvQRangeWidget::slotSelectWholeRange(bool)
{ 
  	setRange(0,values_.count()-1);
}  

//====================================
//   
// MvQRangePlotWidget
//
//====================================

MvQRangePlotWidget::MvQRangePlotWidget(MvQRangeWidget* parent) : 
  QWidget(parent), 
  parent_(parent),
  action_(NoAction),
  hover_(NoHover),
  offset_(15),
  dragRadius_(10)
{
	setMouseTracking(true);
}

QRect MvQRangePlotWidget::rangeRect()
{
	float h=static_cast<float>(rect().height())-2*offset_;
	float w=static_cast<float>(rect().width());
	return QRect(5,offset_+parent_->rangeStartPercent()*h,w-10,(parent_->rangeEndPercent()-parent_->rangeStartPercent())*h);
}

QPolygon MvQRangePlotWidget::minDragShape()
{
	QRect r=rangeRect();
	QPolygon p;
	p << QPoint(r.x(),r.y()+dragRadius_) << 
	     QPoint(r.topRight().x(),r.y()+dragRadius_) << 
	     QPoint(r.topRight().x(),r.y()-dragRadius_/2) << 
	     QPoint(r.center().x(),r.y()-1.5*dragRadius_) << 
	     QPoint(r.x(),r.y()-dragRadius_/2); 
		
	return p;
}

QPolygon MvQRangePlotWidget::maxDragShape()
{
	QRect r=rangeRect();
	QPolygon p;
	p << QPoint(r.x(),r.bottomLeft().y()-dragRadius_) << 
	     QPoint(r.bottomRight().x(),r.bottomLeft().y()-dragRadius_) << 
	     QPoint(r.bottomRight().x(),r.bottomLeft().y()+dragRadius_/2) << 
	     QPoint(r.center().x(),r.bottomLeft().y()+1.5*dragRadius_) << 
	     QPoint(r.x(),r.bottomLeft().y()+dragRadius_/2); 
	     
	return p;     
}

void MvQRangePlotWidget::paintEvent(QPaintEvent* /*event*/)
{
	QPainter painter(this);
	
	//bg
	painter.fillRect(rect(),Qt::white);
  	
	//axis	
	QRect r=rect().adjusted(0,offset_,0,-offset_);
		
	int xp=r.center().x();
	int tickWidth=12;
	QFont font;
	QFontMetrics fm(font);
	
	painter.setPen(Qt::black);
	painter.drawLine(xp,r.y(),xp,r.bottomLeft().y());
	
	//Min tick + text
	painter.drawLine(xp-tickWidth/2,r.y(),xp+tickWidth/2,r.y());
	painter.drawText(QPointF(xp+tickWidth/2+6,r.y()+fm.ascent()/2),QString::number(parent_->startValue()));
	
	//Max tick + text
	painter.drawLine(xp-tickWidth/2,r.bottomLeft().y(),xp+tickWidth/2,r.bottomLeft().y());
	painter.drawText(QPointF(xp+tickWidth/2+6,r.bottomLeft().y()+fm.ascent()/2),QString::number(parent_->endValue()));
	
	//othert ticks + text 
	for(int i=9; i > 5 &&  i < parent_->valueCount()-5; i+=10)
	{
		int yp=r.y()+static_cast<float>(parent_->indexPercent(i))*static_cast<float>(r.height());
		painter.drawLine(xp-tickWidth/2,yp,xp+tickWidth/2,yp);		
		painter.drawText(QPointF(xp+tickWidth/2+6,yp+fm.ascent()/2),QString::number(parent_->value(i)));
	}
	
	//Small ticks
	for(int i=4; i > 3 &&  i < parent_->valueCount()-4; i+=10)
	{
		int yp=r.y()+static_cast<float>(parent_->indexPercent(i))*static_cast<float>(r.height());
		painter.drawLine(xp-tickWidth/4,yp,xp+tickWidth/4,yp);		
	}
	
	//range
	painter.fillRect(rangeRect(),QColor(255,230,191,160));
	painter.setPen(QColor(255,230,191));
	painter.drawRect(rangeRect());
	
	if(action_ == MinDragAction)
	{  
		//QRect minRect=minDragRect();
		//painter.fillRect(minRect,QColor(220,220,220,80));
		//painter.drawRect(minRect);
	}
	else if(action_ == MaxDragAction)
	{
	  	//QRect maxRect=maxDragRect();
		//painter.fillRect(maxRect,QColor(220,220,220,80));
		//painter.drawRect(maxRect);
	} 
	else if(hover_ == MinDragHover)
	{
	  	QPolygon minPoly=minDragShape();
		painter.setBrush(QColor(240,240,240,80));
		painter.drawPolygon(minPoly);
		//painter.drawRect(minRect);
	}
	else if(hover_ == MaxDragHover)
	{
	  	QPolygon maxPoly=maxDragShape();
		painter.setBrush(QColor(240,240,240,80));
		painter.drawPolygon(maxPoly);
		//painter.drawRect(maxRect);
	}
	
}


void MvQRangePlotWidget::mousePressEvent(QMouseEvent *event)
{	  	
	if(minDragShape().containsPoint(event->pos(),Qt::OddEvenFill))
	{
	  	dragPos_=event->pos();
		action_=MinDragAction;
		dragMin_=parent_->rangeStartIndex();
		dragMax_=parent_->rangeEndIndex();
		hover_=NoHover;
		setCursor(QCursor(Qt::SizeVerCursor));
	}
	else if(maxDragShape().containsPoint(event->pos(),Qt::OddEvenFill))
	{
	  	dragPos_=event->pos();
		action_=MaxDragAction;
		dragMin_=parent_->rangeStartIndex();
		dragMax_=parent_->rangeEndIndex();
		hover_=NoHover;	
		setCursor(QCursor(Qt::SizeVerCursor));
	}	
  	else if(rangeRect().contains(event->pos()))
	{
	  	dragPos_=event->pos();
		action_=MoveAction;
		dragMin_=parent_->rangeStartIndex();
		dragMax_=parent_->rangeEndIndex();
		hover_=NoHover;
		setCursor(QCursor(Qt::SizeAllCursor));		
	}	 
}  
  
void MvQRangePlotWidget::mouseMoveEvent(QMouseEvent *event)
{	
  	if(action_== MinDragAction)
	{
		int delta=event->pos().y()-dragPos_.y();		
		float h=static_cast<float>(rect().height())-2*offset_;
		parent_->adjustRangeStart(dragMin_,delta/h);
		update();
	}	
	else if(action_== MaxDragAction)
	{
		int delta=event->pos().y()-dragPos_.y();		
		float h=static_cast<float>(rect().height())-2*offset_;
		parent_->adjustRangeEnd(dragMax_,delta/h);
		update();
	}	
	else if(action_== MoveAction)
	{
		int delta=event->pos().y()-dragPos_.y();		
		float h=static_cast<float>(rect().height())-2*offset_;
		parent_->adjustRange(dragMin_,dragMax_,delta/h);
		update();
	}
	else if(minDragShape().containsPoint(event->pos(),Qt::OddEvenFill))
	{
	  	if(hover_ != MinDragHover)
		{
			hover_=MinDragHover;
			update();
		}	
	}
	else if(maxDragShape().containsPoint(event->pos(),Qt::OddEvenFill))
	{
	  	if(hover_ != MaxDragHover)
		{
		  	hover_=MaxDragHover;
			update();
		}	
	}
	else
	{
	  	if(hover_ != NoHover)
		{
		  	hover_=NoHover;
			update();
		}				
	}	
}  

void MvQRangePlotWidget::mouseReleaseEvent(QMouseEvent* /*event*/)
{	
	if(action_ != NoAction)	
	{
	  	action_=NoAction;
		unsetCursor();
		update();
	}	
}  	
