#include "loqtreewidget.h"
#include <QCheckBox>
#include <QHeaderView>

class CheckableHeader : public QHeaderView {
public:
    explicit CheckableHeader(Qt::Orientation orientation, QWidget *isSelAll) : QHeaderView(orientation), fdIsSelAll(isSelAll) {
        fdIsSelAll->setParent(this);
    }
    QWidget *fdIsSelAll;
protected:
    void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const override;
};
void CheckableHeader::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const{
    QHeaderView::paintSection(painter, rect, logicalIndex);
    if(logicalIndex == 0) fdIsSelAll->setGeometry(rect);
}


LoQTreeWidget::LoQTreeWidget(QWidget *parent) : QTreeWidget(parent), m_checkState(CheckNone) {
    fdIsSelAll = new QCheckBox();
    fdIsSelAll->setStyleSheet("QCheckBox{margin-left: 5px;}");
    m_header = new CheckableHeader(Qt::Horizontal, fdIsSelAll);
    setHeader(m_header);
    setProperty("ssType", "topList");
    connect(fdIsSelAll, SIGNAL(toggled(bool)), this, SLOT(onCheckAll(bool)));
    connect(this, &LoQTreeWidget::itemClicked, this, [this](QTreeWidgetItem *item, int column) {
        if(column > 0) item->setCheckState(0, item->checkState(0) == Qt::Unchecked ? Qt::Checked : Qt::Unchecked);
        adjustCheckState();
    });
    setFocusPolicy(Qt::NoFocus);
}
void LoQTreeWidget::adjustCheckState() {
    bool isAllChecked = true;
    int cnt = topLevelItemCount();
    if(cnt == 0) {
        isAllChecked = false;
        m_checkState = CheckNone;
    } else {
        int k = 0;
        for(int i=0; i<cnt; i++) if(!this->isRowHidden(i,indexFromItem(topLevelItem(i)->parent()))) {
            if(topLevelItem(i)->checkState(0) == Qt::Unchecked) isAllChecked = false;
            else k++;
        }
        if(k > 1) m_checkState = CheckMulti;
        else if(k > 0) m_checkState = CheckOne;
        else m_checkState = CheckNone;
    }
    fdIsSelAll->blockSignals(true);
    fdIsSelAll->setChecked(isAllChecked);
    fdIsSelAll->blockSignals(false);
    emit sigCheckStateChanged(m_checkState);
}

void LoQTreeWidget::onCheckAll(bool checked) {
    int cnt = topLevelItemCount();
    for(int i=0; i<cnt; i++) {
        if(checked) {
            if(this->isRowHidden(i,indexFromItem(topLevelItem(i)->parent()))) topLevelItem(i)->setCheckState(0, Qt::Unchecked);
            else topLevelItem(i)->setCheckState(0, Qt::Checked);
        }
        else topLevelItem(i)->setCheckState(0, Qt::Unchecked);
     }
    adjustCheckState();
}
