/* Copyright (C) 2002 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 <climits> // INT_MIN, etc.
#include <glibmm/vectorutils.h>
#include <gdkmm/contentformats.h>
#include <gtkmm/treeviewcolumn.h>
#include <gtkmm/treeview_private.h>
#include <gtkmm/treemodel.h>
#include <gtkmm/treemodelfilter.h>
#include <gtkmm/treemodelsort.h>
#include <gtkmm/entry.h>
#include <gtk/gtk.h>

using GridLines = Gtk::TreeView::GridLines;

extern "C"
{
static void SignalProxy_Mapping_gtk_callback(GtkTreeView* tree_view, GtkTreePath* path, void* data)
{
  auto the_slot = static_cast<Gtk::TreeView::SlotMapping*>(data);

  try
  {
    (*the_slot)(Glib::wrap(tree_view), Gtk::TreePath(path, true));
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }
}

static gboolean SignalProxy_SearchEqual_gtk_callback(GtkTreeModel* model, int column, const char* key,
                                               GtkTreeIter* iter, void* data)
{
  auto the_slot = static_cast<Gtk::TreeView::SlotSearchEqual*>(data);

  try
  {
    return (*the_slot)(Glib::wrap(model, true), column, key, Gtk::TreeModel::const_iterator(model, iter));
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }

  return 0; // arbitrary value
}

static void SignalProxy_SearchEqual_gtk_callback_destroy(void* data)
{
  delete static_cast<Gtk::TreeView::SlotSearchEqual*>(data);
}

static gboolean SignalProxy_ColumnDrop_gtk_callback(GtkTreeView* tree_view, GtkTreeViewColumn* column,
                                              GtkTreeViewColumn* prev_column,
                                              GtkTreeViewColumn* next_column, void* data)
{
  auto the_slot = static_cast<Gtk::TreeView::SlotColumnDrop*>(data);

  try
  {
    return (*the_slot)(Glib::wrap(tree_view), Glib::wrap(column),
                         Glib::wrap(prev_column), Glib::wrap(next_column));
  }
  catch(...)
  {
    Glib::exception_handlers_invoke();
  }

  return 0; // arbitrary value
}

static void SignalProxy_ColumnDrop_gtk_callback_destroy(void* data)
{
  delete static_cast<Gtk::TreeView::SlotColumnDrop*>(data);
}
} // extern "C"

namespace Gtk
{

int TreeView::insert_column_with_data_func(int position, const Glib::ustring& title, CellRenderer& cell, const SlotTreeCellData& slot)
{
  //Create a copy of the slot. A pointer to this will be passed through the callback's data parameter.
  //It will be deleted when TreeView_Private::gtkmm_SignalProxy_CellData_gtk_callback_destroy() is called.
  auto slot_copy = new SlotTreeCellData(slot);

  return gtk_tree_view_insert_column_with_data_func(
      gobj(), position, title.c_str(), cell.gobj(),
      &TreeView_Private::gtkmm_SignalProxy_CellData_gtk_callback, slot_copy,
      &TreeView_Private::gtkmm_SignalProxy_CellData_gtk_callback_destroy);
}

void TreeView::set_cursor(const TreeModel::Path& path)
{
  gtk_tree_view_set_cursor(gobj(), const_cast<GtkTreePath*>(path.gobj()), nullptr, false);
}

void TreeView::get_cursor(TreeModel::Path& path, TreeViewColumn*& focus_column)
{
  GtkTreePath* pTreePath = nullptr;
  GtkTreeViewColumn* pTreeViewColumn = nullptr;
  gtk_tree_view_get_cursor(gobj(), &pTreePath, &pTreeViewColumn);

  path = TreeModel::Path(pTreePath, false); /* Use the existing underlying GtkTreePath instance without copying and freeing, because gtk_tree_view_get_cursor() gives us ownernship. */
  focus_column = Glib::wrap(pTreeViewColumn);
}

void TreeView::enable_model_drag_source(Gdk::ModifierType start_button_mask, Gdk::DragAction actions)
{
  enable_model_drag_source(Gdk::ContentFormats::create(GTK_TYPE_TREE_ROW_DATA), start_button_mask, actions);
}

void TreeView::enable_model_drag_dest(Gdk::DragAction actions)
{
  enable_model_drag_dest(Gdk::ContentFormats::create(GTK_TYPE_TREE_ROW_DATA), actions);
}

bool TreeView::get_path_at_pos(int x, int y, TreeModel::Path& path, TreeViewColumn*& column, int& cell_x, int& cell_y) const
{
  GtkTreePath* pTreePath = nullptr;
  GtkTreeViewColumn* pTreeViewColumn = nullptr;
  const bool result = gtk_tree_view_get_path_at_pos(const_cast<GtkTreeView*>(gobj()), x, y, &pTreePath, &pTreeViewColumn, &cell_x, &cell_y);

  path = TreeModel::Path(pTreePath, false /* don't take a copy, because the gtk_tree_view_get_path_at_pos() docs say that we must free the path */ );
  column = Glib::wrap(pTreeViewColumn);
  return result;
}

bool TreeView::get_path_at_pos(int x, int y, TreeModel::Path& path) const
{
  GtkTreePath* pTreePath = nullptr;
  const bool result = gtk_tree_view_get_path_at_pos(const_cast<GtkTreeView*>(gobj()), x, y, &pTreePath, nullptr, nullptr, nullptr);

  path = TreeModel::Path(pTreePath, false /* don't take a copy, because the gtk_tree_view_get_path_at_pos() docs say that we must free the path */ );
  return result;
}

int TreeView::insert_column(const Glib::ustring& title, CellRenderer& cell, int position)
{
  return gtk_tree_view_insert_column_with_attributes(
      gobj(), position, const_cast<char*>(title.c_str()), cell.gobj(), nullptr);
}

int TreeView::append_column(const Glib::ustring& title, CellRenderer& cell)
{
  return insert_column(title, cell, -1 /* at the end */);
}

void TreeView::get_drag_dest_row(TreeModel::Path& path, DropPosition& pos) const
{
  GtkTreePath* pTreePath = nullptr;
  gtk_tree_view_get_drag_dest_row(const_cast<GtkTreeView*>(gobj()), &pTreePath, (GtkTreeViewDropPosition*) &pos);
  path = TreeModel::Path(pTreePath, true); //true = take_copy.
}

bool TreeView::get_dest_row_at_pos(int drag_x, int drag_y, TreeModel::Path& path, DropPosition& pos) const
{
  GtkTreePath* pTreePath = nullptr;
  const bool bResult = gtk_tree_view_get_dest_row_at_pos(
      const_cast<GtkTreeView*>(gobj()), drag_x, drag_y, &pTreePath, (GtkTreeViewDropPosition*) &pos);

  path = TreeModel::Path(pTreePath, true); //true = take_copy.
  return bResult;
}

void TreeView::map_expanded_rows(const SlotMapping& slot)
{
  gtk_tree_view_map_expanded_rows(gobj(), &SignalProxy_Mapping_gtk_callback, const_cast<SlotMapping*>(&slot));
}

void TreeView::set_search_equal_func(const SlotSearchEqual& slot)
{
  //Create a copy of the slot. A pointer to this will be passed through the callback's data parameter.
  //It will be deleted when SignalProxy_SearchEqual_gtk_callback_destroy() is called.
  auto slot_copy = new SlotSearchEqual(slot);

  gtk_tree_view_set_search_equal_func(gobj(),
      &SignalProxy_SearchEqual_gtk_callback, slot_copy,
      &SignalProxy_SearchEqual_gtk_callback_destroy);
}

void TreeView::set_column_drag_function(const SlotColumnDrop& slot)
{
  //Create a copt of the slot. A pointer to this will be passed through the callback's data parameter.
  //It will be deleted when SignalProxy_ColumnDrop_gtk_callback_destroy() is called.
  auto slot_copy = new SlotColumnDrop(slot);

  gtk_tree_view_set_column_drag_function(gobj(),
      &SignalProxy_ColumnDrop_gtk_callback, slot_copy,
      &SignalProxy_ColumnDrop_gtk_callback_destroy);

}

void TreeView::unset_column_drag_function()
{
  gtk_tree_view_set_column_drag_function(gobj(),
      nullptr, nullptr, nullptr); /* See GTK+ docs about the nullptrs. */
}

void TreeView::scroll_to_cell(const TreeModel::Path& path, TreeViewColumn& column, float row_align, float col_align)
{
  gtk_tree_view_scroll_to_cell(gobj(), const_cast<GtkTreePath*>(path.gobj()), column.gobj(), TRUE, row_align, col_align);
}

void TreeView::scroll_to_cell(const TreeModel::Path& path, TreeViewColumn& column)
{
  gtk_tree_view_scroll_to_cell(gobj(), const_cast<GtkTreePath*>(path.gobj()), column.gobj(), FALSE, 0.0, 0.0);
}

void TreeView::scroll_to_row(const TreeModel::Path& path, float row_align)
{
  gtk_tree_view_scroll_to_cell(gobj(), const_cast<GtkTreePath*>(path.gobj()), nullptr, TRUE, row_align, 0.0);
}

void TreeView::scroll_to_row(const TreeModel::Path& path)
{
  gtk_tree_view_scroll_to_cell(gobj(), const_cast<GtkTreePath*>(path.gobj()), nullptr, FALSE, 0.0, 0.0);
}

void TreeView::scroll_to_column(TreeViewColumn& column, float col_align)
{
  gtk_tree_view_scroll_to_cell(gobj(), nullptr, column.gobj(), TRUE, 0.0, col_align);
}

void TreeView::scroll_to_column(TreeViewColumn& column)
{
  gtk_tree_view_scroll_to_cell(gobj(), nullptr, column.gobj(), FALSE, 0.0, 0.0);
}

void TreeView::remove_all_columns()
{
  //This method is not in GTK+, but it seems useful.

  //Remove all View columns:
  std::vector<Gtk::TreeView::Column*> vecViewColumns (get_columns());

  for (std::vector<Gtk::TreeView::Column*>::iterator iter (vecViewColumns.begin ()), columns_end (vecViewColumns.end ());
    iter != columns_end;
    ++iter)
  {
    Gtk::TreeView::Column* pViewColumn (*iter);

    if(pViewColumn)
    {
      remove_column(*pViewColumn);
    }
  }
}


CellRenderer* TreeView::get_column_cell_renderer(int n)
{
  auto pColumn = get_column(n);
  if(pColumn)
    return pColumn->get_first_cell();
  else
    return nullptr;
}


const CellRenderer* TreeView::get_column_cell_renderer(int n) const
{
   //Do some const_cast-ing to avoid repetition of code:
  auto pRenderer = const_cast<TreeView*>(this)->get_column_cell_renderer(n);
  return pRenderer;
}

void TreeView::reset_expander_column()
{
  gtk_tree_view_set_expander_column(gobj(), nullptr /* see C docs */);
}

void TreeView::_auto_store_on_cellrenderer_toggle_edited_with_model(const Glib::ustring& path_string,
                                                         int model_column, const Glib::RefPtr<Gtk::TreeModel>& model)
{
  Gtk::TreePath path (path_string);

  //Get the row from the path:
  if(model)
  {
    auto iter = model->get_iter(path);
    if(iter)
    {
      auto row = *iter;

      //Get the new value:
      //This seems to get the old value, not the new one,
      //so we will just NOT the model value ourselves.
      //bool bActive = cell_renderer->get_active();
      bool bActive = false;
      row.get_value(model_column, bActive);
      bActive = !bActive;

      //Store the user's new text in the model:
      row.set_value(model_column, bActive);
    }
  }
}

void TreeView::move_column_to_start(TreeViewColumn& column)
{
  gtk_tree_view_move_column_after(gobj(), (column).gobj(), nullptr /* See C docs */);
}

void TreeView::set_row_separator_func(const SlotRowSeparator& slot)
{
  //Create a copy of the slot. A pointer to this will be passed through the callback's data parameter.
  //It will be deleted when SignalProxy_RowSeparator_gtk_callback_destroy() is called.
  auto slot_copy = new SlotRowSeparator(slot);

  gtk_tree_view_set_row_separator_func(gobj(),
      &TreeView_Private::gtkmm_SignalProxy_RowSeparator_gtk_callback, slot_copy,
      &TreeView_Private::gtkmm_SignalProxy_RowSeparator_gtk_callback_destroy);
}

bool TreeView::get_visible_range(TreeModel::Path& start_path, TreeModel::Path& end_path) const
{
  GtkTreePath* pTreePathStart = nullptr;
  GtkTreePath* pTreePathEnd = nullptr;
  bool result = gtk_tree_view_get_visible_range(const_cast<GtkTreeView*>(gobj()), &pTreePathStart, &pTreePathEnd);

  start_path = TreeModel::Path(pTreePathStart, false /* don't take a copy, because the gtk_tree_view_get_visible_range() docs say that we must free the path */ );
  end_path = TreeModel::Path(pTreePathEnd, false /* don't take a copy, because the gtk_tree_view_get_visible_range() docs say that we must free the path */ );
  return result;
}

void TreeView::unset_model()
{
  gtk_tree_view_set_model(gobj(), nullptr);
}

bool
TreeView::get_tooltip_context_path(int x, int y,
                                   bool keyboard_tip,
                                   TreeModel::Path& path)
{
  GtkTreePath* cpath = nullptr;

  gboolean result =
    gtk_tree_view_get_tooltip_context(gobj(),
                                      x, y,
                                      keyboard_tip,
                                      nullptr,
                                      &cpath,
                                      nullptr);

  //If result is false, cpath is not modified, it's still nullptr.
  //wrap() can handle that situation.
  path = Glib::wrap(cpath, false /* take_copy=false */);

  return result;
}

bool
TreeView::get_tooltip_context_iter(int x, int y,
                                   bool keyboard_tip,
                                   Gtk::TreeModel::iterator& iter)
{
  GtkTreeIter src_iter;

  gboolean result =
    gtk_tree_view_get_tooltip_context(gobj(),
                                      x, y,
                                      keyboard_tip,
                                      nullptr,
                                      nullptr,
                                      &src_iter);

  iter = TreeModel::iterator(gtk_tree_view_get_model(this->gobj()), &src_iter);

  return result;
}

bool TreeView::is_blank_at_pos(int x, int y, TreePath& path, TreeViewColumn*& column, int& cell_x, int& cell_y) const
{
  GtkTreePath* cpath = nullptr;
  GtkTreeViewColumn* pcolumn = nullptr;
  const bool result = gtk_tree_view_is_blank_at_pos(const_cast<GtkTreeView*>(gobj()), x, y, &cpath, &pcolumn, &(cell_x), &(cell_y));

  path = TreePath(cpath, false /* take ownership instead of taking a copy */);
  column = Glib::wrap(pcolumn);
  return result;
}

bool TreeView::is_blank_at_pos(int x, int y) const
{
  return gtk_tree_view_is_blank_at_pos(const_cast<GtkTreeView*>(gobj()), x, y, nullptr, nullptr, nullptr, nullptr);
}

void TreeView::unset_drag_dest_row()
{
  // The C docs specify that a 0 path means unset.
  gtk_tree_view_set_drag_dest_row(gobj(), nullptr, GTK_TREE_VIEW_DROP_BEFORE /* Arbitrary. Ignored anyway. */);
}

void TreeView::unset_row_separator_func()
{
  gtk_tree_view_set_row_separator_func(gobj(), nullptr, nullptr, nullptr);
}

namespace TreeView_Private
{
// Specializations of _connect_auto_store_editable_signal_handler()

//bool specialization:
template<>
void _connect_auto_store_editable_signal_handler<bool>(Gtk::TreeView* this_p,
  Gtk::CellRenderer* pCellRenderer, const Gtk::TreeModelColumn<bool>& model_column)
{
  Gtk::CellRendererToggle* pCellToggle = dynamic_cast<Gtk::CellRendererToggle*>(pCellRenderer);
  if(pCellToggle)
  {
    //Set the appropriate property,
    pCellToggle->property_activatable() = true;

    //Connect to the appropriate signal, sending the model_column too

    sigc::slot<void(const Glib::ustring&, int)> slot_temp =
      sigc::bind<-1>(
        sigc::mem_fun(*this_p, &Gtk::TreeView::_auto_store_on_cellrenderer_toggle_edited_with_model),
        this_p->get_model()
      );

    pCellToggle->signal_toggled().connect(
      sigc::bind<-1>(
        slot_temp,
        model_column.index()
      )
    );

    //We use bind<-1> instead of bind because some compilers need the extra hint.
  }
}

//int specialization:
template<>
void _connect_auto_store_editable_signal_handler<int>(Gtk::TreeView* this_p,
  Gtk::CellRenderer* pCellRenderer, const Gtk::TreeModelColumn<int>& model_column)
{
  _connect_auto_store_numeric_editable_signal_handler<int>(this_p, pCellRenderer, model_column);
}

//unsigned int specialization:
template<>
void _connect_auto_store_editable_signal_handler<unsigned int>(Gtk::TreeView* this_p,
  Gtk::CellRenderer* pCellRenderer, const Gtk::TreeModelColumn<unsigned int>& model_column)
{
  _connect_auto_store_numeric_editable_signal_handler<unsigned int>(this_p, pCellRenderer, model_column);
}

//long specialization:
template<>
void _connect_auto_store_editable_signal_handler<long>(Gtk::TreeView* this_p,
  Gtk::CellRenderer* pCellRenderer, const Gtk::TreeModelColumn<long>& model_column)
{
  _connect_auto_store_numeric_editable_signal_handler<long>(this_p, pCellRenderer, model_column);
}

//unsigned long specialization:
template<>
void _connect_auto_store_editable_signal_handler<unsigned long>(Gtk::TreeView* this_p,
  Gtk::CellRenderer* pCellRenderer, const Gtk::TreeModelColumn<unsigned long>& model_column)
{
  _connect_auto_store_numeric_editable_signal_handler<unsigned long>(this_p, pCellRenderer, model_column);
}

//float specialization:
template<>
void _connect_auto_store_editable_signal_handler<float>(Gtk::TreeView* this_p,
  Gtk::CellRenderer* pCellRenderer, const Gtk::TreeModelColumn<float>& model_column)
{
  _connect_auto_store_numeric_editable_signal_handler<float>(this_p, pCellRenderer, model_column);
}

//double specialization:
template<>
void _connect_auto_store_editable_signal_handler<double>(Gtk::TreeView* this_p,
  Gtk::CellRenderer* pCellRenderer, const Gtk::TreeModelColumn<double>& model_column)
{
  _connect_auto_store_numeric_editable_signal_handler<double>(this_p, pCellRenderer, model_column);
}

// Specializations of _convert_from_ustring_to_numeric_type()

// Floating point specializations
template<>
float _convert_from_ustring_to_numeric_type<float>(const Glib::ustring& text)
{
  return std::strtof(text.c_str(), nullptr);
}

template<>
long double _convert_from_ustring_to_numeric_type<long double>(const Glib::ustring& text)
{
  return std::strtold(text.c_str(), nullptr);
}

// Integral specializations
template<>
short _convert_from_ustring_to_numeric_type<short>(const Glib::ustring& text)
{
  const auto result = std::strtol(text.c_str(), nullptr, 0);
  return (result < SHRT_MIN) ? SHRT_MIN :
        ((result > SHRT_MAX) ? SHRT_MAX : static_cast<short>(result));
}

template<>
unsigned short _convert_from_ustring_to_numeric_type<unsigned short>(const Glib::ustring& text)
{
  const auto result = std::strtoul(text.c_str(), nullptr, 0);
  return (result > USHRT_MAX) ? USHRT_MAX : static_cast<unsigned short>(result);
}

template<>
int _convert_from_ustring_to_numeric_type<int>(const Glib::ustring& text)
{
  const auto result = std::strtol(text.c_str(), nullptr, 0);
  return (result < INT_MIN) ? INT_MIN :
        ((result > INT_MAX) ? INT_MAX : static_cast<int>(result));
}

template<>
unsigned int _convert_from_ustring_to_numeric_type<unsigned int>(const Glib::ustring& text)
{
  const auto result = std::strtoul(text.c_str(), nullptr, 0);
  return (result > UINT_MAX) ? UINT_MAX : static_cast<unsigned int>(result);
}

template<>
long _convert_from_ustring_to_numeric_type<long>(const Glib::ustring& text)
{
  return std::strtol(text.c_str(), nullptr, 0);
}

template<>
unsigned long _convert_from_ustring_to_numeric_type<unsigned long>(const Glib::ustring& text)
{
  return std::strtoul(text.c_str(), nullptr, 0);
}

template<>
long long _convert_from_ustring_to_numeric_type<long long>(const Glib::ustring& text)
{
  return std::strtoll(text.c_str(), nullptr, 0);
}

template<>
unsigned long long _convert_from_ustring_to_numeric_type<unsigned long long>(const Glib::ustring& text)
{
  return std::strtoull(text.c_str(), nullptr, 0);
}

} // namespace TreeView_Private

} // namespace Gtk
