/* Copyright (C) 2020 The gtkmm Development Team
 *
 * 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.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 */

#include <gtk/gtk.h>

namespace
{
extern "C"
{
static GListModel* TreeListModel_CreateModelFunc(gpointer item, gpointer user_data)
{
  auto slot = static_cast<Gtk::TreeListModel::SlotCreateModel*>(user_data);
  auto result = (*slot)(Glib::wrap(G_OBJECT(item), true));
  if (result)
    return G_LIST_MODEL(result->gobj_copy());
  else
    return nullptr;
}

static void TreeListModel_CreateModelFunc_destroy(void* data)
{
  delete static_cast<Gtk::TreeListModel::SlotCreateModel*>(data);
}
} // extern "C"
} // anonymous namespace

namespace Gtk
{

// The only way to set create_func is to use gtk_tree_list_model_new.
TreeListModel::TreeListModel(const Glib::RefPtr<Gio::ListModel>& root,
                             const SlotCreateModel& slot_create,
                             bool passthrough, bool autoexpand)
:
  Glib::ObjectBase(nullptr),
  Glib::Object(G_OBJECT(gtk_tree_list_model_new(
      G_LIST_MODEL(root->gobj_copy()), passthrough, autoexpand,
      &TreeListModel_CreateModelFunc,
      new SlotCreateModel(slot_create),
      &TreeListModel_CreateModelFunc_destroy)))
{
}

} // namespace Gtk
