/***************************** 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 <QDebug>
#include <QHBoxLayout>
#include <QLabel>

#include "MvQSliderLine.h"

#include "LineFactory.h"
#include "RequestPanel.h"
#include "Parameter.h"

#include "MvQSlider.h"

MvQSliderLine::MvQSliderLine(RequestPanel& owner,const Parameter& param) :
		   MvQRequestPanelLine(owner,param) 
{

	QWidget *sliderParent=new QWidget(parentWidget_);
	QHBoxLayout* layout= new QHBoxLayout(parentWidget_);
	sliderParent->setLayout(layout);
	owner_.addWidget(sliderParent,row_,3);
	
	//Slider
  	slider_=new MvQSlider(sliderParent);
	slider_->setOrientation(Qt::Horizontal);
	slider_->setTickPosition(QSlider::TicksBelow);
  	layout->addWidget(slider_);
	
	Request r=param.interfaceRequest();
	r.print();
	
	const char *min;	
	r.getValue(min,"min",0);	
	int minVal=QString(min).toInt();
	
	const char *max;	
	r.getValue(max,"max",0);	
	int maxVal=QString(max).toInt();
	
	const char *step;	
	r.getValue(step,"step",0);	
	int stepVal=QString(step).toInt();
	
	const char *def;	
	r.getValue(def,"default",0);	
	int defVal=QString(def).toInt();class QRadioButton;

	const char *direction;	
	r.getValue(direction,"direction",0);	
	QString directionVal(direction);

	slider_->setRange(minVal,maxVal);
	slider_->setSingleStep(stepVal);
	slider_->setPageStep(stepVal);
	
	if(stepVal != 0) 
	{
	  	int n=(maxVal-minVal)/stepVal;
	  	
	  	if(n < 15)
	  		slider_->setTickInterval(stepVal);
		else
		{
		  	for(int i=2; i < n && i < 100; i++)
			{
			  	if((maxVal-minVal)/(i*stepVal) < 15)
				{  	
				  	slider_->setTickInterval(i*stepVal);
					break;
				}
			}
		}	
	}
	
	if(direction && strcmp(direction,"max_on_left") == 0)
	{
	  	slider_->setInvertedAppearance(true);
	}
	
	//Label
	valueLabel_=new QLabel(sliderParent);
	layout->addWidget(valueLabel_);
	
	slotValueChanged(defVal);
	
	connect(slider_,SIGNAL(valueChanged(int)),
		this,SLOT(slotValueChanged(int)));	
  	
}

MvQSliderLine::~MvQSliderLine()
{
}
	
void MvQSliderLine::refresh(const vector<string>& values)
{
	if(values.size() > 0)
	{
		QString s=QString::fromStdString(values[0]);
		slider_->setSliderPosition(s.toInt());
	}	
		
	//changed_ = false;
}	
	
void MvQSliderLine::slotValueChanged(int value)
{	
	QString s=QString::number(value);
  	owner_.set(param_.name(),s.toStdString()),
	valueLabel_->setText(s);
}

static LineMaker<MvQSliderLine> maker1("slider");
