//
// Created by Krad on 2021/11/23.
//

#include "SlideableTableView.h"
#include <QScrollBar>
#include <QMouseEvent>
#include <QApplication>
#include <math.h>

SlideableTableView::SlideableTableView(QWidget *parent) : QTableView(parent) {

}

SlideableTableView::~SlideableTableView() {

}

void SlideableTableView::mousePressEvent(QMouseEvent *ev) {
    isDragging = true;
    ox = ev->pos().x();
    oy = ev->pos().y();
    ov = this->verticalScrollBar()->value();
    QTableView::mousePressEvent(ev);
}

void SlideableTableView::mouseMoveEvent(QMouseEvent *ev) {
    if (!isDragging)
    {
        QTableView::mouseMoveEvent(ev);
        return;
    } else{
        if (this->verticalScrollBar()->isVisible())
        {
            int nv = (int)round(((double)ov*30.0+((double)(oy-ev->pos().y())))/30.0);
            int max = this->verticalScrollBar()->maximum();
            int min = this->verticalScrollBar()->minimum();
            printf("max:%d, min:%d, nv:%d\r\n", max, min, nv);
            nv = nv>max?max:(nv<min?min:nv);
            this->verticalScrollBar()->setValue(nv);
        }
//        if (this->verticalScrollBar()->isVisible())
//        {
//            this->verticalScrollBar()->setPageStep(this->viewport()->height());
//            this->verticalScrollBar()->setRange(0,this->height());
//            int nv =this->verticalScrollBar()->value()+(oy-ev->pos().y());
//            int max = this->verticalScrollBar()->maximum();
//            int min = this->verticalScrollBar()->minimum();
//            printf("max:%d, min:%d, nv:%d\r\n", max, min, nv);
//            nv = nv>max?max:(nv<min?min:nv);
//
////            this->verticalScrollBar()->setValue(nv);
//            return;
//        }
    }
    QTableView::mouseMoveEvent(ev);
}

void SlideableTableView::mouseReleaseEvent(QMouseEvent *ev) {
    if (!isDragging)
    {
        isDragging = false;
    }

//    if (this->verticalScrollBar()->isVisible())
//    {
//        QApplication::sendEvent(this->verticalScrollBar(),ev);
//    }
    QTableView::mouseReleaseEvent(ev);
}
