/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <searchresults.hxx>

#include <svtools/simptabl.hxx>
#include <vcl/fixed.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <dociter.hxx>
#include <document.hxx>
#include <tabvwsh.hxx>
#include <strings.hrc>
#include <sc.hrc>
#include <scresid.hxx>

namespace sc {

SearchResultsDlg::SearchResultsDlg(SfxBindings* _pBindings, weld::Window* pParent)
    : SfxDialogController(pParent, "modules/scalc/ui/searchresults.ui", "SearchResultsDialog")
    , aSkipped(ScResId(SCSTR_SKIPPED))
    , mpBindings(_pBindings)
    , mpDoc(nullptr)
    , mxList(m_xBuilder->weld_tree_view("results"))
    , mxSearchResults(m_xBuilder->weld_label("lbSearchResults"))
{
    mxList->set_size_request(mxList->get_approximate_digit_width() * 50, mxList->get_height_rows(15));

    std::vector<int> aWidths;
    aWidths.push_back(mxList->get_approximate_digit_width() * 10);
    aWidths.push_back(mxList->get_approximate_digit_width() * 10);
    mxList->set_column_fixed_widths(aWidths);
    mxList->connect_changed(LINK(this, SearchResultsDlg, ListSelectHdl));
}

SearchResultsDlg::~SearchResultsDlg()
{
}

namespace
{
    class ListWrapper {
        weld::TreeView& mrList;
    public:
        size_t mnCount = 0;
        static const size_t mnMaximum = 1000;
        ListWrapper(weld::TreeView& rList)
            : mrList(rList)
        {
            mrList.clear();
            mrList.freeze();
        }
        ~ListWrapper()
        {
            mrList.thaw();
        }
        void Insert(const OUString &rTabName,
                    const ScAddress &rPos,
                    formula::FormulaGrammar::AddressConvention eConvention,
                    const OUString &rText)
        {
            if (mnCount++ < mnMaximum)
            {
                mrList.append_text(rTabName);
                int nPos = mrList.n_children() - 1;
                mrList.set_text(nPos, rPos.Format(ScRefFlags::ADDR_ABS,
                                      nullptr, eConvention), 1);
                mrList.set_text(nPos, rText, 2);
            }
        }
    };
}

void SearchResultsDlg::FillResults( ScDocument* pDoc, const ScRangeList &rMatchedRanges, bool bCellNotes )
{
    ListWrapper aList(*mxList);
    std::vector<OUString> aTabNames = pDoc->GetAllTableNames();
    SCTAB nTabCount = aTabNames.size();

    // tdf#92160 - too many results blow the widget's mind
    size_t nMatchMax = rMatchedRanges.size();
    if (nMatchMax > ListWrapper::mnMaximum)
        nMatchMax = ListWrapper::mnMaximum;

    if (bCellNotes)
    {
        for (size_t i = 0, n = nMatchMax; i < n; ++i)
        {
            /* TODO: a CellNotes iterator would come handy and might speed
             * things up a little, though we only loop through the
             * search/replace result positions here. */
            ScRange const & rRange( rMatchedRanges[i] );
            // Bear in mind that mostly the range is one address position
            // or a column or a row joined.
            ScAddress aPos( rRange.aStart );
            for ( ; aPos.Tab() <= rRange.aEnd.Tab(); aPos.IncTab())
            {
                if (aPos.Tab() >= nTabCount)
                    break;  // can this even happen? we just searched on existing sheets ...
                for (aPos.SetCol( rRange.aStart.Col()); aPos.Col() <= rRange.aEnd.Col(); aPos.IncCol())
                {
                    for (aPos.SetRow( rRange.aStart.Row()); aPos.Row() <= rRange.aEnd.Row(); aPos.IncRow())
                    {
                        const ScPostIt* pNote = pDoc->GetNote( aPos);
                        if (pNote)
                            aList.Insert(aTabNames[aPos.Tab()], aPos,
                                         pDoc->GetAddressConvention(),
                                         pNote->GetText());
                    }
                }
            }
        }
    }
    else
    {
        for (size_t i = 0, n = nMatchMax; i < n; ++i)
        {
            ScCellIterator aIter(pDoc, rMatchedRanges[i]);
            for (bool bHas = aIter.first(); bHas; bHas = aIter.next())
            {
                const ScAddress& aPos = aIter.GetPos();
                if (aPos.Tab() >= nTabCount)
                    // Out-of-bound sheet index.
                    continue;

                aList.Insert(aTabNames[aPos.Tab()], aPos,
                             pDoc->GetAddressConvention(),
                             pDoc->GetString(aPos));
            }
        }
    }

    OUString aTotal(ScResId(SCSTR_TOTAL, aList.mnCount));
    OUString aSearchResults = aTotal.replaceFirst("%1", OUString::number(aList.mnCount));
    if (aList.mnCount > ListWrapper::mnMaximum)
        aSearchResults += " " + ScGlobal::ReplaceOrAppend( aSkipped, "%1", OUString::number( ListWrapper::mnMaximum ) );
    mxSearchResults->set_label(aSearchResults);

    mpDoc = pDoc;
}

void SearchResultsDlg::Close()
{
    if (mpBindings)
    {
        // Remove this dialog from the view frame after the dialog gets
        // dismissed, else it would keep popping up endlessly!
        SfxDispatcher* pDispacher = mpBindings ->GetDispatcher();
        SfxBoolItem aItem(SID_SEARCH_RESULTS_DIALOG, false);
        if (pDispacher)
        {
            pDispacher->ExecuteList(SID_SEARCH_RESULTS_DIALOG,
                SfxCallMode::SYNCHRON | SfxCallMode::RECORD, { &aItem });
        }
    }

    SfxDialogController::Close();
}

IMPL_LINK_NOARG( SearchResultsDlg, ListSelectHdl, weld::TreeView&, void )
{
    if (!mpDoc)
        return;

    int nEntry = mxList->get_selected_index();
    OUString aTabStr = mxList->get_text(nEntry, 0);
    OUString aPosStr = mxList->get_text(nEntry, 1);

    SCTAB nTab = -1;
    if (!mpDoc->GetTable(aTabStr, nTab))
        // No sheet with specified name.
        return;

    ScAddress aPos;
    ScRefFlags nRes = aPos.Parse(aPosStr, mpDoc, mpDoc->GetAddressConvention());
    if (!(nRes & ScRefFlags::VALID))
        // Invalid address string.
        return;

    // Jump to the cell.
    ScTabViewShell* pScViewShell = ScTabViewShell::GetActiveViewShell();
    pScViewShell->SetTabNo(nTab);
    pScViewShell->SetCursor(aPos.Col(), aPos.Row());
    pScViewShell->AlignToCursor(aPos.Col(), aPos.Row(), SC_FOLLOW_JUMP);
}

SearchResultsDlgWrapper::SearchResultsDlgWrapper(
    vcl::Window* _pParent, sal_uInt16 nId, SfxBindings* pBindings, SfxChildWinInfo* /*pInfo*/)
    : SfxChildWindow(_pParent, nId)
    , m_xDialog(new SearchResultsDlg(pBindings, _pParent->GetFrameWeld()))
{
    SetController(m_xDialog);
}

SearchResultsDlgWrapper::~SearchResultsDlgWrapper() {}

SfxChildWinInfo SearchResultsDlgWrapper::GetInfo() const
{
    SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
    aInfo.bVisible = false;
    return aInfo;
}

SFX_IMPL_CHILDWINDOW_WITHID(SearchResultsDlgWrapper, SID_SEARCH_RESULTS_DIALOG);

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
