/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the Collabora Office 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 <svx/dialog/ThemeDialog.hxx>
#include <docmodel/theme/ColorSet.hxx>
#include <docmodel/theme/Theme.hxx>
#include <svx/ColorSets.hxx>
#include <vcl/svapp.hxx>
#include <comphelper/kit.hxx>
#include <vcl/virdev.hxx>

namespace svx
{
ThemeDialog::ThemeDialog(weld::Window* pParent, model::Theme* pTheme)
    : GenericDialogController(pParent, u"svx/ui/themedialog.ui"_ustr, u"ThemeDialog"_ustr)
    , ThemeColorsPaneBase(m_xBuilder->weld_icon_view(u"iconview_theme_colors"_ustr))
    , mpTheme(pTheme)
    , mxAdd(m_xBuilder->weld_button(u"button_add"_ustr))
{
    mxAdd->connect_clicked(LINK(this, ThemeDialog, ButtonClicked));

    initColorSets(pTheme);
}

ThemeDialog::~ThemeDialog()
{
    if (mxSubDialog)
        mxSubDialog->response(RET_CANCEL);
}

void ThemeDialog::onColorSetActivated()
{
    if (!comphelper::COKit::isActive())
        m_xDialog->response(RET_OK);
}

void ThemeDialog::runThemeColorEditDialog()
{
    if (mxSubDialog)
        return;

    mxSubDialog = std::make_shared<svx::ThemeColorEditDialog>(getDialog(), *mpCurrentColorSet);

    weld::DialogController::runAsync(mxSubDialog, [this](sal_uInt32 nResult) {
        if (nResult != RET_OK)
        {
            mxAdd->set_sensitive(true);
            mxSubDialog = nullptr;
            return;
        }
        auto aColorSet = mxSubDialog->getColorSet();
        if (!aColorSet.getName().isEmpty())
        {
            ColorSets::get().insert(aColorSet);
            initColorSets(mpTheme);

            // The new theme was appended to maColorSets, so it is the last
            // entry the icon view received. initColorSets() may skip hidden
            // entries (e.g. the legacy "LibreOffice" theme), so the icon
            // view can have fewer rows than maColorSets — address the row
            // via n_children() rather than the model size.
            const int nLastVisiblePos = mxIconViewThemeColors->n_children() - 1;
            if (nLastVisiblePos >= 0)
            {
                mxIconViewThemeColors->select(nLastVisiblePos);
                mpCurrentColorSet
                    = std::make_shared<model::ColorSet>(maColorSets[maColorSets.size() - 1]);
            }
        }
        mxAdd->set_sensitive(true);
        mxSubDialog = nullptr;
    });
}

IMPL_LINK(ThemeDialog, ButtonClicked, weld::Button&, rButton, void)
{
    mxAdd->set_sensitive(false);
    if (mpCurrentColorSet && mxAdd.get() == &rButton)
    {
        runThemeColorEditDialog();
    }
}

} // end svx namespace

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