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

#include <QtGlobal>
#include <QDebug>
#include <QLineEdit>
#include <QPushButton>
#include <QTreeView>
#include <QHeaderView>

#include "MvQTreeViewSearchLine.h"
#include "TreeModelMatchCollector.h"

TreeViewSearchLine::TreeViewSearchLine(QWidget* parent) :
    AbstractSearchLine(parent)
{
    label_->hide();
    // closeTb_->hide();

    // It makes no sense for a tree
    actionHighlightAll_->setEnabled(false);

    collector_ = new TreeModelMatchCollector;

    connect(matchModeCb_, SIGNAL(currentIndexChanged(int)),
            this, SLOT(matchModeChanged(int)));
}

TreeViewSearchLine::~TreeViewSearchLine()
{
    Q_ASSERT(collector_);
    delete collector_;
}

// This should only be called once!!
void TreeViewSearchLine::setView(QTreeView* view)
{
    // We should disconnect from the previous view ...
    view_ = view;

    // We detect when the sorting changes in the view
    connect(view_->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)),
            this, SLOT(slotSortHappened(int, Qt::SortOrder)));

    // At this point the model has to be set on the view!!!
    assert(view_->model() != nullptr);

    // We detect when the model is reset
    connect(view_->model(), SIGNAL(modelReset()),
            this, SLOT(slotUpdate()));

    // We should detect when the model changes!!!!
    connect(view_->model(), SIGNAL(dataChanged(QModelIndex, QModelIndex)),
            this, SLOT(slotUpdate(QModelIndex, QModelIndex)));

    collector_->setModel(view_->model());
}

void TreeViewSearchLine::setColumns(QVector<int> columns)
{
    columns_ = columns;
    refreshSearch();
}

void TreeViewSearchLine::refreshSearch()
{
    collector_->clear();
    currentResultItem_ = -1;
    slotFind(searchLine_->text());
}

void TreeViewSearchLine::slotFind(QString txt)
{
    if (!view_)
        return;

    // If the search term is empty we just clear everything
    if (txt.simplified().isEmpty()) {
        collector_->clear();
        currentResultItem_ = 0;
        updateButtons(false);
        return;
    }

    QModelIndex current = view_->currentIndex();

    // Set the match flags
    Qt::MatchFlags flags = Qt::MatchRecursive;
    if (caseSensitive())
        flags = flags | Qt::MatchCaseSensitive;

    if (matchModeCb_->currentMatchMode() == StringMatchMode::ContainsMatch) {
        flags = flags | Qt::MatchContains;
    }
    else if (matchModeCb_->currentMatchMode() == StringMatchMode::WildcardMatch) {
        flags = flags | Qt::MatchWildcard;
    }
    else if (matchModeCb_->currentMatchMode() == StringMatchMode::RegexpMatch) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
        flags = flags | Qt::MatchRegularExpression;
#else
        flags = flags | Qt::MatchRegExp;
#endif
    }

    // Get the matching indexes.
    // QAbstractItemModel::match() does not work properly. Even if MatchRecursive
    // is set it only searches in the current branch!!
    collector_->match(txt, columns_, flags, current);

    // The view needs to be rerendered!
    view_->dataChanged(QModelIndex(), QModelIndex());

    if (collector_->itemCount() > 0) {
        int startPos = collector_->startItemPos();
        Q_ASSERT(startPos >= 0);
        selectIndex(collector_->items()[startPos]);
        currentResultItem_ = startPos;
        updateButtons(true);
    }
    else {
        currentResultItem_ = 0;
        updateButtons(false);
    }
}

void TreeViewSearchLine::slotFindNext()
{
    if (!view_)
        return;

    if (status_ == true && collector_->items().count() > 0) {
        if (currentResultItem_ >= 0 &&
            collector_->items()[currentResultItem_] != view_->currentIndex()) {
            // This will find the one after the currentIdex! So we can
            // return here.
            currentResultItem_ = -1;
            collector_->clear();
            slotFind(searchLine_->text());
            return;
        }

        currentResultItem_++;
        if (currentResultItem_ >= collector_->items().count()) {
            currentResultItem_ = 0;
        }
        selectIndex(collector_->items()[currentResultItem_]);
    }
}

void TreeViewSearchLine::slotFindPrev()
{
    if (!view_)
        return;

    if (status_ == true && collector_->items().count() > 0) {
        if (currentResultItem_ >= 0 &&
            collector_->items()[currentResultItem_] != view_->currentIndex()) {
            // This will find the one after the currentIdex!
            // So we need to step back.
            currentResultItem_ = -1;
            collector_->clear();
            slotFind(searchLine_->text());
        }

        currentResultItem_--;
        if (currentResultItem_ < 0) {
            currentResultItem_ = collector_->items().count() - 1;
        }
        selectIndex(collector_->items()[currentResultItem_]);
    }
}

void TreeViewSearchLine::selectIndex(const QModelIndex& index)
{
    if (!view_)
        return;

    view_->setCurrentIndex(index);
    view_->scrollTo(index);
    // emit indexSelected(index);
}

// Called when sorting changed in the view
void TreeViewSearchLine::slotSortHappened(int, Qt::SortOrder)
{
    slotUpdate();
}

void TreeViewSearchLine::slotUpdate()
{
    collector_->clear();
    currentResultItem_ = -1;
    slotFind(searchLine_->text());

    QSet<QString> s;
    collector_->allValues(s);
    setCompleter(s);
}

void TreeViewSearchLine::slotUpdate(const QModelIndex&, const QModelIndex&)
{
    slotUpdate();
}

void TreeViewSearchLine::matchModeChanged(int)
{
    if (matchModeCb_->currentMatchMode() == StringMatchMode::ContainsMatch)
        actionWholeWords_->setEnabled(true);
    else
        actionWholeWords_->setEnabled(false);

    refreshSearch();
}

void TreeViewSearchLine::on_actionCaseSensitive__toggled(bool b)
{
    AbstractSearchLine::on_actionCaseSensitive__toggled(b);
    refreshSearch();
}

void TreeViewSearchLine::on_actionWholeWords__toggled(bool b)
{
    AbstractSearchLine::on_actionWholeWords__toggled(b);
    refreshSearch();
}

void TreeViewSearchLine::slotClose()
{
    AbstractSearchLine::slotClose();
    clear();
    collector_->clear();
    currentResultItem_ = -1;
    // clearHighlights();
}
