// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "findplugin.h"

#include "../actionmanager/actioncontainer.h"
#include "../actionmanager/actionmanager.h"
#include "../actionmanager/command.h"
#include "../coreconstants.h"
#include "../coreplugintr.h"
#include "../icontext.h"
#include "../icore.h"
#include "../session.h"
#include "currentdocumentfind.h"
#include "findtoolbar.h"
#include "findtoolwindow.h"
#include "ifindfilter.h"
#include "itemviewfind.h"
#include "searchresultwindow.h"
#include "textfindconstants.h"

#include <extensionsystem/pluginmanager.h>

#include <utils/algorithm.h>
#include <utils/itemviews.h>
#include <utils/qtcassert.h>

#include <QApplication>
#include <QMenu>
#include <QStringListModel>
#include <QVector>
#include <QAction>

/*!
    \namespace Core::Internal::ItemDataRoles
    \internal
*/

/*!
    \class Core::Find
    \inmodule QtCreator
    \internal
*/

using namespace Qt;
using namespace Utils;

namespace {
    const int MAX_COMPLETIONS = 50;
}

namespace Core {

struct CompletionEntry
{
    friend QDebug operator<<(QDebug d, const CompletionEntry &e)
    {
        QDebugStateSaver saver(d);
        d.noquote();
        d.nospace();
        d << "CompletionEntry(\"" << e.text << "\", flags="
          << "0x" << QString::number(e.findFlags, 16) << ')';
        return d;
    }

    QString text;
    FindFlags findFlags;
};

class CompletionModel : public QAbstractListModel
{
public:
    explicit CompletionModel(QObject *p = nullptr) : QAbstractListModel(p) {}

    int rowCount(const QModelIndex & = QModelIndex()) const override { return m_entries.size(); }

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;

    void restore(const Store &s);
    Store save() const;

    void updateCompletion(const QString &text, FindFlags f);

private:
    QVector<CompletionEntry> m_entries;
};

QVariant CompletionModel::data(const QModelIndex &index, int role) const
{
    if (index.isValid()) {
        const CompletionEntry &entry = m_entries.at(index.row());
        switch (role) {
        case Qt::DisplayRole:
        case Qt::EditRole:
            return QVariant(entry.text);
        case Find::CompletionModelFindFlagsRole:
            return QVariant(int(entry.findFlags));
        default:
            break;
        }
    }
    return QVariant();
}

static Utils::Key completionSettingsTextKey() { return "Text"; }
static Utils::Key completionSettingsFlagsKey() { return "Flags"; }

void CompletionModel::restore(const Store &s)
{
    beginResetModel();
    const QStringList texts = s.value(completionSettingsTextKey()).toStringList();
    const QList<FindFlags> flags
        = transform(s.value(completionSettingsFlagsKey()).toList(), [](const QVariant &v) {
              return FindFlags(v.toInt());
          });
    const int size = texts.size();
    m_entries.clear();
    m_entries.reserve(size);
    for (int i = 0; i < size; ++i) {
        CompletionEntry entry;
        entry.text = texts.at(i);
        entry.findFlags = i < flags.size() ? flags.at(i) : FindFlags();
        if (!entry.text.isEmpty())
            m_entries.append(entry);
    }
    endResetModel();
}

Store CompletionModel::save() const
{
    if (m_entries.isEmpty())
        return {};
    const QStringList texts = transform(m_entries, [](const CompletionEntry &e) { return e.text; });
    const QVariantList flags = transform(m_entries, [](const CompletionEntry &e) {
        return QVariant::fromValue(int(e.findFlags));
    });
    Store s;
    s.insert(completionSettingsTextKey(), texts);
    s.insert(completionSettingsFlagsKey(), flags);
    return s;
}

void CompletionModel::updateCompletion(const QString &text, FindFlags f)
{
    if (text.isEmpty())
         return;
     beginResetModel();
     Utils::erase(m_entries, Utils::equal(&CompletionEntry::text, text));
     m_entries.prepend({text, f});
     while (m_entries.size() > MAX_COMPLETIONS)
         m_entries.removeLast();
     endResetModel();
}

class FindPrivate : public QObject
{
public:
    bool isAnyFilterEnabled() const;
    void writeSettings();
    void setFindFlag(FindFlag flag, bool enabled);
    static void updateCompletion(const QString &text, QStringList &completions,
                                 QStringListModel *model);
    void setupMenu();
    void setupFilterMenuItems();
    void readSettings();

    Internal::CurrentDocumentFind *m_currentDocumentFind = nullptr;
    Internal::FindToolBar *m_findToolBar = nullptr;
    Internal::FindToolWindow *m_findDialog = nullptr;
    SearchResultWindow *m_searchResultWindow = nullptr;
    FindFlags m_findFlags = DontFindGeneratedFiles;
    CompletionModel m_findCompletionModel;
    QStringListModel m_replaceCompletionModel;
    QStringList m_replaceCompletions;
    QAction *m_openFindDialog = nullptr;
};

Find *m_instance = nullptr;
FindPrivate *d = nullptr;

void Find::destroy()
{
    delete m_instance;
    m_instance = nullptr;
    if (d) {
        delete d->m_currentDocumentFind;
        delete d->m_findToolBar;
        delete d->m_findDialog;
        ExtensionSystem::PluginManager::removeObject(d->m_searchResultWindow);
        delete d->m_searchResultWindow;
        delete d;
    }
}

Find *Find::instance()
{
    return m_instance;
}

void Find::initialize()
{
    QTC_ASSERT(!m_instance, return);
    m_instance = new Find;

    d = new FindPrivate;
    d->setupMenu();

    d->m_currentDocumentFind = new Internal::CurrentDocumentFind;

    d->m_findToolBar = new Internal::FindToolBar(d->m_currentDocumentFind);
    IContext::attach(d->m_findToolBar, Context(Constants::C_FINDTOOLBAR));

    d->m_findDialog = new Internal::FindToolWindow;
    d->m_searchResultWindow = new SearchResultWindow(d->m_findDialog);
    ExtensionSystem::PluginManager::addObject(d->m_searchResultWindow);

    QObject::connect(ICore::instance(), &ICore::saveSettingsRequested, d, &FindPrivate::writeSettings);
    QObject::connect(
        SessionManager::instance(),
        &SessionManager::aboutToSaveSession,
        d,
        &FindPrivate::writeSettings);
    QObject::connect(
        SessionManager::instance(), &SessionManager::sessionLoaded, d, &FindPrivate::readSettings);

    Utils::Internal::setViewSearchCallback([](QAbstractItemView *view, int role) {
        Aggregation::aggregate({view, new ItemViewFind(view, role)});
    });
}

void Find::extensionsInitialized()
{
    d->setupFilterMenuItems();
}

void Find::aboutToShutdown()
{
    d->m_findToolBar->setVisible(false);
    d->m_findToolBar->setParent(nullptr);
    d->m_currentDocumentFind->removeConnections();
}

bool FindPrivate::isAnyFilterEnabled() const
{
    return Utils::anyOf(m_findDialog->findFilters(), &IFindFilter::isEnabled);
}

void Find::openFindDialog(IFindFilter *filter, const QString &findString)
{
    d->m_currentDocumentFind->acceptCandidate();
    const QString currentFindString = [findString] {
        if (!findString.isEmpty())
            return findString;
        if (d->m_findToolBar->isVisible()
            && QApplication::focusWidget() == d->m_findToolBar->focusWidget()
            && !d->m_findToolBar->getFindText().isEmpty()) {
            return d->m_findToolBar->getFindText();
        }
        if (d->m_currentDocumentFind->isEnabled())
            return d->m_currentDocumentFind->currentFindString();
        return QString();
    }();
    if (!currentFindString.isEmpty())
        d->m_findDialog->setFindText(currentFindString);
    d->m_findDialog->setCurrentFilter(filter);
    SearchResultWindow::instance()->openNewSearchPanel();
}

void FindPrivate::setupMenu()
{
    ActionContainer *medit = ActionManager::actionContainer(Constants::M_EDIT);
    ActionContainer *mfind = ActionManager::createMenu(Constants::M_FIND);
    medit->addMenu(mfind, Constants::G_EDIT_FIND);
    mfind->menu()->setTitle(Tr::tr("&Find/Replace"));
    mfind->appendGroup(Constants::G_FIND_CURRENTDOCUMENT);
    mfind->appendGroup(Constants::G_FIND_FILTERS);
    mfind->appendGroup(Constants::G_FIND_FLAGS);
    mfind->appendGroup(Constants::G_FIND_ACTIONS);
    mfind->addSeparator(Constants::G_FIND_FLAGS);
    mfind->addSeparator(Constants::G_FIND_ACTIONS);

    ActionContainer *mfindadvanced = ActionManager::createMenu(Constants::M_FIND_ADVANCED);
    mfindadvanced->menu()->setTitle(Tr::tr("Advanced Find"));
    mfind->addMenu(mfindadvanced, Constants::G_FIND_FILTERS);

    ActionBuilder openFindDialog(this, Constants::ADVANCED_FIND);
    openFindDialog.setText(Tr::tr("Open Advanced Find..."));
    openFindDialog.setIconText(Tr::tr("Advanced..."));
    openFindDialog.bindContextAction(&m_openFindDialog);
    openFindDialog.setDefaultKeySequence(Tr::tr("Ctrl+Shift+F"));
    openFindDialog.addToContainer(Constants::M_FIND_ADVANCED);
    openFindDialog.addOnTriggered(this, [] { Find::openFindDialog(nullptr); });
}

static QString filterActionName(const IFindFilter *filter)
{
    return QLatin1String("    ") + filter->displayName();
}

void FindPrivate::setupFilterMenuItems()
{
    bool haveEnabledFilters = false;
    const Id base("FindFilter.");
    const QList<IFindFilter *> sortedFilters = Utils::sorted(IFindFilter::allFindFilters(),
                                                             &IFindFilter::displayName);
    for (IFindFilter *filter : sortedFilters) {
        ActionBuilder findScope(this, base.withSuffix(filter->id()));
        findScope.setText(filterActionName(filter));
        bool isEnabled = filter->isEnabled();
        if (isEnabled)
            haveEnabledFilters = true;
        findScope.setEnabled(isEnabled);
        findScope.setDefaultKeySequence(filter->defaultShortcut());
        findScope.setCommandAttribute(Command::CA_UpdateText);
        findScope.addToContainer(Constants::M_FIND_ADVANCED);
        findScope.addOnTriggered(this, [filter] { Find::openFindDialog(filter); });

        QAction *findScopeAction = findScope.contextAction();
        connect(filter, &IFindFilter::enabledChanged, this, [filter, findScopeAction] {
            findScopeAction->setEnabled(filter->isEnabled());
            d->m_openFindDialog->setEnabled(d->isAnyFilterEnabled());
        });
        connect(filter, &IFindFilter::displayNameChanged, this, [filter, findScopeAction] {
            findScopeAction->setText(filterActionName(filter));
        });
    }
    d->m_findDialog->setFindFilters(sortedFilters);
    d->m_openFindDialog->setEnabled(haveEnabledFilters);
}

FindFlags Find::findFlags()
{
    return d->m_findFlags;
}

void Find::setCaseSensitive(bool sensitive)
{
    d->setFindFlag(FindCaseSensitively, sensitive);
}

void Find::setWholeWord(bool wholeOnly)
{
    d->setFindFlag(FindWholeWords, wholeOnly);
}

void Find::setIgnoreBinaryFiles(bool ignoreBinaryFiles)
{
    d->setFindFlag(DontFindBinaryFiles, ignoreBinaryFiles);
}

void Find::setIgnoreGeneratedFiles(bool ignoreGeneratedFiles)
{
    d->setFindFlag(Utils::DontFindGeneratedFiles, ignoreGeneratedFiles);
}

void Find::setBackward(bool backward)
{
    d->setFindFlag(FindBackward, backward);
}

void Find::setRegularExpression(bool regExp)
{
    d->setFindFlag(FindRegularExpression, regExp);
}

void Find::setPreserveCase(bool preserveCase)
{
    d->setFindFlag(FindPreserveCase, preserveCase);
}

void FindPrivate::setFindFlag(FindFlag flag, bool enabled)
{
    bool hasFlag = m_findFlags & flag;
    if ((hasFlag && enabled) || (!hasFlag && !enabled))
        return;
    if (enabled)
        m_findFlags |= flag;
    else
        m_findFlags &= ~flag;
    if (flag != FindBackward)
        emit m_instance->findFlagsChanged();
}

bool Find::hasFindFlag(FindFlag flag)
{
    return d->m_findFlags & flag;
}

void FindPrivate::writeSettings()
{
    // save in session
    Store s;
    if (m_findFlags & FindBackward)
        s.insert("Backward", true);
    if (m_findFlags & FindCaseSensitively)
        s.insert("CaseSensitively", true);
    if (m_findFlags & DontFindBinaryFiles)
        s.insert("IgnoreBinaryFiles", true);
    if (!(m_findFlags & DontFindGeneratedFiles))
        s.insert("IgnoreGeneratedFiles", false);
    if (m_findFlags & FindWholeWords)
        s.insert("WholeWords", true);
    if (m_findFlags & FindRegularExpression)
        s.insert("RegularExpression", true);
    if (m_findFlags & FindPreserveCase)
        s.insert("PreserveCase", true);
    const Store completion = m_findCompletionModel.save();
    if (!completion.isEmpty())
        s.insert("FindCompletions", variantFromStore(completion));
    if (!m_replaceCompletions.isEmpty())
        s.insert("ReplaceStrings", m_replaceCompletions);
    const Store toolbar = m_findToolBar->save();
    if (!toolbar.isEmpty())
        s.insert("ToolBar", variantFromStore(toolbar));
    const Store advanced = m_findDialog->save();
    if (!advanced.isEmpty())
        s.insert("AdvancedSearch", variantFromStore(advanced));
    SessionManager::setValue("Find", variantFromStore(s));
}

void FindPrivate::readSettings()
{
    const Store s = storeFromVariant(SessionManager::value("Find"));
    if (!s.empty()) {
        {
            QSignalBlocker blocker(m_instance);
            Find::setBackward(s.value("Backward", false).toBool());
            Find::setCaseSensitive(s.value("CaseSensitively", false).toBool());
            Find::setWholeWord(s.value("WholeWords", false).toBool());
            Find::setRegularExpression(s.value("RegularExpression", false).toBool());
            Find::setPreserveCase(s.value("PreserveCase", false).toBool());
            Find::setIgnoreBinaryFiles(s.value("IgnoreBinaryFiles", false).toBool());
            Find::setIgnoreGeneratedFiles(s.value("IgnoreGeneratedFiles", true).toBool());
        }
        m_findCompletionModel.restore(storeFromVariant(s.value("FindCompletions")));
        m_replaceCompletions = s.value("ReplaceStrings").toStringList();
        m_replaceCompletionModel.setStringList(m_replaceCompletions);
        m_findToolBar->restore(storeFromVariant(s.value("ToolBar")));
        m_findDialog->restore(storeFromVariant(s.value("AdvancedSearch")));
    }
    emit m_instance->findFlagsChanged(); // would have been done in the setXXX methods above
}

void Find::updateFindCompletion(const QString &text, FindFlags flags)
{
    d->m_findCompletionModel.updateCompletion(text, flags);
}

void Find::updateReplaceCompletion(const QString &text)
{
    FindPrivate::updateCompletion(text, d->m_replaceCompletions, &d->m_replaceCompletionModel);
}

void FindPrivate::updateCompletion(const QString &text, QStringList &completions, QStringListModel *model)
{
    if (text.isEmpty())
        return;
    completions.removeAll(text);
    completions.prepend(text);
    while (completions.size() > MAX_COMPLETIONS)
        completions.removeLast();
    model->setStringList(completions);
}

void Find::setUseFakeVim(bool on)
{
    if (d->m_findToolBar)
        d->m_findToolBar->setUseFakeVim(on);
}

void Find::openFindToolBar(FindDirection direction)
{
    if (d->m_findToolBar) {
        d->m_findToolBar->setBackward(direction == FindBackwardDirection);
        d->m_findToolBar->openFindToolBar();
    }
}

QAbstractListModel *Find::findCompletionModel()
{
    return &(d->m_findCompletionModel);
}

QStringListModel *Find::replaceCompletionModel()
{
    return &(d->m_replaceCompletionModel);
}

} // namespace Core
