#include "scrollarea.h"
#include <QApplication>
#include <QDebug>
#include <QMouseEvent>
#include <QScrollBar>

template <typename T>
inline T qClamp(T v, T min, T max) {return qMin<T>(max, qMax<T>(min, v));}


SHSScrollArea::SHSScrollArea(QWidget * parent): QScrollArea(parent) {
	setMouseTracking(true);
	//animation.setEasingCurve(QEasingCurve::OutQuad);
	//connect(&animation, &QVariantAnimation::valueChanged, this, [this](QVariant v){cur_transition = v.toDouble(); aw->update();});
	//connect(&animation, &QVariantAnimation::finished, this, [this](){endMove();});
}


SHSScrollArea::~SHSScrollArea() {
}


void SHSScrollArea::timerEvent(QTimerEvent * e) {
	if (speed.manhattanLength() < 10) stop();
	//qDebug() << speed << spos;
	spos -= speed / 100;
	speed /= 1.05;
	verticalScrollBar()->setValue(spos.y());
	horizontalScrollBar()->setValue(spos.x());
}


void SHSScrollArea::mousePressEvent(QMouseEvent * e) {
	speed = QPointF();
	stop();
	tm.restart();
	press_pos = e->pos();
}


void SHSScrollArea::mouseReleaseEvent(QMouseEvent * e) {
	stop();
	timer = startTimer(10);
}


void SHSScrollArea::mouseMoveEvent(QMouseEvent * e) {
	if (e->buttons() != Qt::LeftButton) return;
	double el = tm.elapsed();
	tm.restart();
	speed = e->pos() - press_pos;
	press_pos = e->pos();
	verticalScrollBar()->setValue(verticalScrollBar()->value() - speed.y());
	horizontalScrollBar()->setValue(horizontalScrollBar()->value() - speed.x());
	spos = QPointF(horizontalScrollBar()->value(), verticalScrollBar()->value());
	speed /= (el + 1) / 1000.;
}


void SHSScrollArea::stop() {
	if (timer == 0) return;
	killTimer(timer);
	timer = 0;
}
