/**
 * Copyright (C) 2023-2026 Linaro Limited (or its affiliates). All rights reserved.
 * Copyright (C) 2012-2023 Arm Limited (or its affiliates).
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */

#include "findsystem.h"

#include "find/currentdocumentfind.h"
#include "find/findtoolbar.h"

namespace TextEditor {

FindSystem* FindSystem::static_instance = NULL;

FindSystem::FindSystem() :
    QObject(),
    m_findToolBarInstance(NULL),
    m_currentDocumentFind(NULL)
{
}

FindSystem*
FindSystem::instance()
{
    if (!static_instance)
        static_instance = new FindSystem();
    return static_instance;
}

void
FindSystem::init()
{
    if (!m_findToolBarInstance || !m_currentDocumentFind)
    {
        m_currentDocumentFind = new Find::Internal::CurrentDocumentFind;
        m_findToolBarInstance = new Find::Internal::FindToolBar(m_currentDocumentFind);
    }
}

void
FindSystem::openFindToolBar(bool focus)
{
    init();
    m_findToolBarInstance->openFindToolBar(focus);
}

void
FindSystem::openFindToolBar(QString &initialText, bool focus)
{
    init();
    m_findToolBarInstance->openFindToolBar(focus, initialText);
}

void
FindSystem::openFindToolBarInDirection(bool backwards)
{
    init();
    m_findToolBarInstance->setBackward(backwards);
    openFindToolBar();
}

void
FindSystem::closeFindToolBar()
{
    if (m_findToolBarInstance)
        m_findToolBarInstance->close();
}

void
FindSystem::setUseFakeVim(bool on)
{
    init();
    m_findToolBarInstance->setUseFakeVim(on);
}

void
FindSystem::findNext()
{
    init();
    m_findToolBarInstance->triggerFindNext();
}

void
FindSystem::findPrevious()
{
    init();
    m_findToolBarInstance->triggerFindPrevious();
}

void
FindSystem::find(bool reverse)
{
    init();
    if (reverse)
        m_findToolBarInstance->triggerFindPrevious();
    else
        m_findToolBarInstance->triggerFindNext();
}

void
FindSystem::setCaseSensitive(bool b)
{
    m_findToolBarInstance->setCaseSensitive(b);
}

QWidget * FindSystem::findToolBarWidget()
{
    return m_findToolBarInstance;
}

} // end namespace TextEditor

namespace Find {

// declared in textfindconstants.h
QTextDocument::FindFlags textDocumentFlagsForFindFlags(FindFlags flags)
{
    QTextDocument::FindFlags textDocFlags;
    if (flags & Find::FindBackward)
        textDocFlags |= QTextDocument::FindBackward;
    if (flags & Find::FindCaseSensitively)
        textDocFlags |= QTextDocument::FindCaseSensitively;
    if (flags & Find::FindWholeWords)
        textDocFlags |= QTextDocument::FindWholeWords;
    return textDocFlags;
}

}
