/* 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>
#include <gtkmm/builder.h>

namespace
{
using BuilderScope_get_type_from_name_vfunc_functype = GType (*)(
  GtkBuilderScope* self, GtkBuilder* builder, const char* type_name);

BuilderScope_get_type_from_name_vfunc_functype BuilderScope_get_type_from_name_vfunc_funcptr;

extern "C"
{
static GType BuilderScope_get_type_from_name_vfunc_c_callback(
  GtkBuilderScope* self, GtkBuilder* builder, const char* type_name)
{
  return BuilderScope_get_type_from_name_vfunc_funcptr(self, builder, type_name);
}
} // extern "C"
} // anonymous namespace

namespace Gtk
{

// Allow GtkBuilder to instantiate a gtkmm derived GType instead of the regular
// GTK GType, so we can, for instance, use our vfuncs and default signal handlers.
// static
GType BuilderScope_Class::get_type_from_name_vfunc_callback(
  GtkBuilderScope* self, GtkBuilder* builder, const char* type_name)
{
  if (!type_name)
    return G_TYPE_INVALID;

  GType gtype = G_TYPE_INVALID;

  // If a TreeModel (such as ListStore or TreeStore) is being built,
  // Buildable_Class may have requested no search for gtkmm-derived types.
  // See https://bugzilla.gnome.org/show_bug.cgi?id=742637
  const auto obj = dynamic_cast<Builder*>(
    Glib::ObjectBase::_get_current_wrapper((GObject*)builder));
  if (!(obj && obj->no_gtkmm_derived_types))
  {
    // See if there is a gtkmm version of the gclass:
    Glib::ustring classname_prefixed ("gtkmm__"); // gtkmm uses a prefix
    classname_prefixed += type_name;

    gtype = g_type_from_name(classname_prefixed.c_str());
  }

  if (gtype == G_TYPE_INVALID) // If it's not a registered typename
  {
    const auto base = static_cast<BaseClassType*>(
      // Get the parent interface of the interface (The original underlying C interface).
      g_type_interface_peek_parent(
      // Get the interface.
      g_type_interface_peek(G_OBJECT_GET_CLASS(self), CppObjectType::get_type())));

    // Call the original underlying C function.
    if (base && base->get_type_from_name)
      gtype = (*base->get_type_from_name)(self, builder, type_name);
    else // If that's not possible, just use the normal GType.
      gtype = g_type_from_name(type_name);
  }

  return gtype;
}

} // namespace Gtk
