/* Copyright (C) 2003 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 <https://www.gnu.org/licenses/>.
 */

#include <glibmm/vectorutils.h>

#include <gtkmm/cellarea.h>
#include <gtk/gtk.h>

extern "C"
{
static void SignalProxy_CellData_gtk_callback(GtkCellLayout* /* cell_layout */, GtkCellRenderer* /* cell */, GtkTreeModel* tree_model, GtkTreeIter* iter, gpointer data)
{
  auto the_slot = static_cast<Gtk::CellLayout::SlotCellData*>(data);

  try
  {
    //We ignore the cell, because that was given as an argument to the connecting method, so the caller should know which one it is already.
    //And we ignore the tree_model because that can be obtained from the iter or from the CellLayout itself.
    (*the_slot)(Gtk::TreeModel::const_iterator(tree_model, iter));
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
}

static void SignalProxy_CellData_gtk_callback_destroy(void* data)
{
  delete static_cast<Gtk::CellLayout::SlotCellData*>(data);
}
} // extern "C"

namespace Gtk
{

void CellLayout::add_attribute(const Glib::PropertyProxy_Base& property, const TreeModelColumnBase& column)
{
  gtk_cell_layout_add_attribute(gobj(),
      (GtkCellRenderer*) property.get_object()->gobj(), property.get_name(), column.index());
}

void CellLayout::add_attribute(CellRenderer& cell, const Glib::ustring& attribute, const TreeModelColumnBase& column)
{
  gtk_cell_layout_add_attribute(gobj(),
      (GtkCellRenderer*) cell.gobj(), attribute.c_str(), column.index());
}

void CellLayout::set_cell_data_func(CellRenderer& cell, const SlotCellData& slot)
{
  // Create a copy of the slot object.  A pointer to this will be passed
  // through the callback's data parameter.  It will be deleted
  // when SignalProxy_CellData_gtk_callback_destroy() is called.
  auto slot_copy = new SlotCellData(slot);

  gtk_cell_layout_set_cell_data_func(gobj(), cell.gobj(),
      &SignalProxy_CellData_gtk_callback, slot_copy,
      &SignalProxy_CellData_gtk_callback_destroy);
}

CellRenderer* CellLayout::get_first_cell()
{
  auto vecCellRenderers = get_cells();
  if(!vecCellRenderers.empty())
    return vecCellRenderers[0];
  else
    return nullptr;
}

const CellRenderer* CellLayout::get_first_cell() const
{
  //Do some const_cast-ing to avoid repetition of code:
  return const_cast<CellLayout*>(this)->get_first_cell();
}

} //namespace Gtk
