/* Copyright (C) 1998-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 <glibmm/vectorutils.h>

#include <gtk/gtk.h>
#include <glib.h>
#include <gtkmm/textmark.h>
#include <gtkmm/textiter.h>

namespace
{
extern "C"
{
static void SignalProxy_CommitNotify_gtk_callback(GtkTextBuffer* /* buffer */,
  GtkTextBufferNotifyFlags flags, guint position, guint length,
  void* user_data)
{
  auto the_slot = static_cast<Gtk::TextBuffer::SlotCommitNotify*>(user_data);

  try
  {
    (*the_slot)(static_cast<Gtk::TextBuffer::NotifyFlags>(flags), position, length);
  }
  catch (...)
  {
    Glib::exception_handlers_invoke();
  }
}

static void SignalProxy_CommitNotify_gtk_callback_destroy(void* data)
{
  delete static_cast<Gtk::TextBuffer::SlotCommitNotify*>(data);
}
} // extern "C"
} // anonymous namespace

namespace Gtk
{

typedef TextChildAnchor ChildAnchor; //Help the code-generator so that it does not have to fully qualify this type in the .cc file.

TextBuffer::TextBuffer(const Glib::RefPtr<TagTable>& tag_table)
:
  _CONSTRUCT("tag_table", Glib::unwrap(tag_table))
{}

Glib::RefPtr<TextBuffer::Tag> TextBuffer::create_tag(const Glib::ustring& tag_name)
{
  //gtk_text_buffer_create_tag takes a varargs list of property names and values.
  //gtkmm coders should use the Tag.set_* method instead.
  return Glib::wrap(gtk_text_buffer_create_tag(gobj(), tag_name.c_str(), nullptr), true); //true = take_copy.
  //We have to take a copy because gtk_text_buffer_create_tag() doesn't ref for us, for no real reason.
}

Glib::RefPtr<TextBuffer::Tag> TextBuffer::create_tag()
{
  //gtk_text_buffer_create_tag takes a varargs list of property names and values.
  //gtkmm coders should use the Tag.set_* method instead.
  return Glib::wrap(gtk_text_buffer_create_tag(gobj(), nullptr, nullptr), true); //true = take_copy.
  //We have to take a copy because gtk_text_buffer_create_tag() doesn't ref for us, for no real reason.
}

Glib::RefPtr<TextBuffer::Mark>
TextBuffer::create_mark(const TextBuffer::iterator& where, bool left_gravity)
{
  return Glib::wrap(gtk_text_buffer_create_mark(
      gobj(), nullptr, const_cast<GtkTextIter*>(where.gobj()), left_gravity),
      true); // acquire reference
}

TextBuffer::iterator TextBuffer::get_iter_at_line_offset(int line_number, int char_offset)
{
  iterator iter;
  gtk_text_buffer_get_iter_at_line_offset(gobj(), iter.gobj(), line_number, char_offset);
  return iter;
}

TextBuffer::const_iterator TextBuffer::get_iter_at_line_offset(int line_number, int char_offset) const
{
  return const_cast<TextBuffer*>(this)->get_iter_at_line_offset(line_number, char_offset);
}

TextBuffer::iterator TextBuffer::get_iter_at_line_index(int line_number, int byte_index)
{
  iterator iter;
  gtk_text_buffer_get_iter_at_line_index(gobj(), iter.gobj(), line_number, byte_index);
  return iter;
}

TextBuffer::const_iterator TextBuffer::get_iter_at_line_index(int line_number, int byte_index) const
{
  return const_cast<TextBuffer*>(this)->get_iter_at_line_index(line_number, byte_index);
}

TextBuffer::iterator TextBuffer::get_iter_at_offset(int char_offset)
{
  iterator iter;
  gtk_text_buffer_get_iter_at_offset(gobj(), iter.gobj(), char_offset);
  return iter;
}

TextBuffer::const_iterator TextBuffer::get_iter_at_offset(int char_offset) const
{
  return const_cast<TextBuffer*>(this)->get_iter_at_offset(char_offset);
}

TextBuffer::iterator TextBuffer::get_iter_at_line(int line_number)
{
  iterator iter;
  gtk_text_buffer_get_iter_at_line(gobj(), iter.gobj(), line_number);
  return iter;
}

TextBuffer::const_iterator TextBuffer::get_iter_at_line(int line_number) const
{
  return const_cast<TextBuffer*>(this)->get_iter_at_line(line_number);
}

TextBuffer::iterator TextBuffer::begin()
{
  iterator iter;
  gtk_text_buffer_get_start_iter(gobj(), iter.gobj());
  return iter;
}

TextBuffer::const_iterator TextBuffer::begin() const
{
  return const_cast<TextBuffer*>(this)->begin();
}

TextBuffer::iterator TextBuffer::end()
{
  iterator iter;
  gtk_text_buffer_get_end_iter(gobj(), iter.gobj());
  return iter;
}

TextBuffer::const_iterator TextBuffer::end() const
{
  return const_cast<TextBuffer*>(this)->end();
}

void TextBuffer::get_bounds(iterator& range_begin, iterator& range_end)
{
  gtk_text_buffer_get_bounds(gobj(), range_begin.gobj(), range_end.gobj());
}

void TextBuffer::get_bounds(const_iterator& range_begin, const_iterator& range_end) const
{
  gtk_text_buffer_get_bounds(const_cast<GtkTextBuffer*>(gobj()), range_begin.gobj(), range_end.gobj());
}

TextBuffer::iterator TextBuffer::get_iter_at_mark(const Glib::RefPtr<Mark>& mark)
{
  iterator iter;
  gtk_text_buffer_get_iter_at_mark(gobj(), iter.gobj(), mark->gobj());
  return iter;
}

TextBuffer::iterator TextBuffer::get_iter_at_mark(GtkTextMark* mark)
{
  iterator iter;
  gtk_text_buffer_get_iter_at_mark(gobj(), iter.gobj(), mark);
  return iter;
}

TextBuffer::const_iterator TextBuffer::get_iter_at_mark(const Glib::RefPtr<Mark>& mark) const
{
  return const_cast<TextBuffer*>(this)->get_iter_at_mark(mark);
}

void TextBuffer::set_text(const Glib::ustring& text)
{
  gtk_text_buffer_set_text(gobj(), text.data(), text.bytes());
}

void TextBuffer::set_text(const char* text_begin, const char* text_end)
{
  gtk_text_buffer_set_text(gobj(), text_begin, text_end - text_begin);
}

TextBuffer::iterator TextBuffer::insert(const iterator& pos, const Glib::ustring& text)
{
  // gtk_text_buffer_insert() modifies the iterator, but that's not the
  // STL way so we give it something that we don't mind it modifying.
  iterator iterCopy (pos);
  gtk_text_buffer_insert(gobj(), iterCopy.gobj(), text.data(), text.bytes());

  // According to the gtk_text_buffer_insert() docs, the "default signal handler
  // revalidates it to point to the end of the inserted text".
  return iterCopy;
}

TextBuffer::iterator TextBuffer::insert(const iterator& pos, const char* text_begin, const char* text_end)
{
  // gtk_text_buffer_insert() modifies the iterator, but that's not the
  // STL way so we give it something that we don't mind it modifying.
  iterator iterCopy (pos);
  gtk_text_buffer_insert(gobj(), iterCopy.gobj(), text_begin, text_end - text_begin);

  // According to the gtk_text_buffer_insert() docs, the "default signal handler
  // revalidates it to point to the end of the inserted text".
  return iterCopy;
}

TextBuffer::iterator TextBuffer::insert_paintable(const iterator& pos, const Glib::RefPtr<Gdk::Paintable>& paintable)
{
  iterator iterCopy (pos);
  gtk_text_buffer_insert_paintable(gobj(), iterCopy.gobj(), paintable->gobj());
  return iterCopy;
}

TextBuffer::iterator TextBuffer::insert_child_anchor(const iterator& pos,
                                                     const Glib::RefPtr<ChildAnchor>& anchor)
{
  // Copy the iterator. It might be changed because it is used as a signal parameter internally.
  iterator iterCopy (pos);
  gtk_text_buffer_insert_child_anchor(gobj(), iterCopy.gobj(), Glib::unwrap(anchor));
  return iterCopy;
}

Glib::RefPtr<ChildAnchor> TextBuffer::create_child_anchor(const iterator& pos)
{
  // Copy the iterator. It might be changed because it is used as a signal parameter internally.
  iterator iterCopy (pos);
  return Glib::wrap(gtk_text_buffer_create_child_anchor(gobj(), iterCopy.gobj()),
                    true); // The function does not do a ref for us.
}

void TextBuffer::insert_at_cursor(const Glib::ustring& text)
{
  gtk_text_buffer_insert_at_cursor(gobj(), text.data(), text.bytes());
}

void TextBuffer::insert_at_cursor(const char* text_begin, const char* text_end)
{
  gtk_text_buffer_insert_at_cursor(gobj(), text_begin, text_end - text_begin);
}

std::pair<TextBuffer::iterator,bool>
TextBuffer::insert_interactive(const iterator& pos, const Glib::ustring& text, bool default_editable)
{
  // Since we have to copy the iterator anyway we can as well create the
  // std::pair now.  That saves another copy later (mind you, TextIter is
  // a heavy struct), and allows modern compilers to apply the return value
  // optimization.
  std::pair<iterator,bool> pair_iter_success (pos, false);

  pair_iter_success.second = gtk_text_buffer_insert_interactive(
      gobj(), pair_iter_success.first.gobj(), text.data(), text.bytes(), default_editable);

  return pair_iter_success;
}

std::pair<TextBuffer::iterator,bool>
TextBuffer::insert_interactive(const iterator& pos, const char* text_begin, const char* text_end,
                               bool default_editable)
{
  // Since we have to copy the iterator anyway we can as well create the
  // std::pair now.  That saves another copy later (mind you, TextIter is
  // a heavy struct), and allows modern compilers to apply the return value
  // optimization.
  std::pair<iterator,bool> pair_iter_success (pos, false);

  pair_iter_success.second =  gtk_text_buffer_insert_interactive(
      gobj(), pair_iter_success.first.gobj(), text_begin, text_end - text_begin, default_editable);

  return pair_iter_success;
}

bool TextBuffer::insert_interactive_at_cursor(const Glib::ustring& text, bool default_editable)
{
  return gtk_text_buffer_insert_interactive_at_cursor(
      gobj(), text.data(), text.bytes(), default_editable);
}

bool TextBuffer::insert_interactive_at_cursor(const char* text_begin, const char* text_end,
                                              bool default_editable)
{
  return gtk_text_buffer_insert_interactive_at_cursor(
      gobj(), text_begin, text_end - text_begin, default_editable);
}

TextBuffer::iterator TextBuffer::insert_with_tag(const iterator& pos, const Glib::ustring& text,
                                                 const Glib::RefPtr<Tag>& tag)
{
  // gtk_text_buffer_insert_with_tags() invalidates the iterator, but this lets us recreate it later.
  const int offset = pos.get_offset();

  iterator iterCopy (pos);
  gtk_text_buffer_insert_with_tags(
      gobj(), iterCopy.gobj(), text.data(), text.bytes(), tag->gobj(), nullptr);

  return get_iter_at_offset(offset + text.size());
}

TextBuffer::iterator TextBuffer::insert_with_tag(const iterator& pos,
                                                 const char* text_begin, const char* text_end,
                                                 const Glib::RefPtr<Tag>& tag)
{
  // gtk_text_buffer_insert_with_tags() invalidates the iterator, but this lets us recreate it later.
  const int offset = pos.get_offset();

  iterator iterCopy (pos);
  gtk_text_buffer_insert_with_tags(
      gobj(), iterCopy.gobj(), text_begin, text_end - text_begin, tag->gobj(), nullptr);

  return get_iter_at_offset(offset + (text_end - text_begin));
}

TextBuffer::iterator TextBuffer::insert_with_tag(const iterator& pos, const Glib::ustring& text,
                                                 const Glib::ustring& tag_name)
{
  // gtk_text_buffer_insert_with_tags() invalidates the iterator, but this lets us recreate it later.
  const int offset = pos.get_offset();

  iterator iterCopy (pos);
  gtk_text_buffer_insert_with_tags_by_name(
      gobj(), iterCopy.gobj(), text.data(), text.bytes(), tag_name.c_str(), nullptr);

  return get_iter_at_offset(offset + text.size());
}

TextBuffer::iterator TextBuffer::insert_with_tag(const iterator& pos,
                                                 const char* text_begin, const char* text_end,
                                                 const Glib::ustring& tag_name)
{
  // gtk_text_buffer_insert_with_tags() invalidates the iterator, but this lets us recreate it later.
  const int offset = pos.get_offset();

  iterator iterCopy (pos);
  gtk_text_buffer_insert_with_tags_by_name(
      gobj(), iterCopy.gobj(), text_begin, text_end - text_begin, tag_name.c_str(), nullptr);

  return get_iter_at_offset(offset + (text_end - text_begin));
}

TextBuffer::iterator TextBuffer::insert_with_tags(const iterator& pos, const Glib::ustring& text,
                                                  const std::vector< Glib::RefPtr<Tag> >& tags)
{
  const char *const text_begin = text.data();
  return insert_with_tags(pos, text_begin, text_begin + text.bytes(), tags);
}

TextBuffer::iterator TextBuffer::insert_with_tags(const iterator& pos,
                                                  const char* text_begin, const char* text_end,
                                                  const std::vector< Glib::RefPtr<Tag> >& tags)
{
  const int start_offset = pos.get_offset();
  iterator range_end (insert(pos, text_begin, text_end));

  GtkTextIter range_begin;
  gtk_text_buffer_get_iter_at_offset(gobj(), &range_begin, start_offset);

  Glib::ArrayHandler<Glib::RefPtr<Tag> >::ArrayKeeperType array_keeper (Glib::ArrayHandler<Glib::RefPtr<Tag> >::vector_to_array(tags));

  GtkTextTag* const* const tags_begin = array_keeper.data();
  GtkTextTag* const* const tags_end   = tags_begin + tags.size();

  for (GtkTextTag* const* ptag = tags_begin; ptag != tags_end; ++ptag)
  {
    gtk_text_buffer_apply_tag(gobj(), *ptag, &range_begin, range_end.gobj());
  }

  return range_end;
}

TextBuffer::iterator TextBuffer::insert_with_tags_by_name(const iterator& pos, const Glib::ustring& text,
                                                          const std::vector<Glib::ustring>& tag_names)
{
  const char *const text_begin = text.data();
  return insert_with_tags_by_name(pos, text_begin, text_begin + text.bytes(), tag_names);
}

TextBuffer::iterator TextBuffer::insert_with_tags_by_name(const iterator& pos,
                                                          const char* text_begin, const char* text_end,
                                                          const std::vector<Glib::ustring>& tag_names)
{
  // gtk_buffer_insert_with_tags_by_name() is a convenience wrapper, so it's kind of OK to reimplement it:

  const int start_offset = pos.get_offset();
  iterator range_end (insert(pos, text_begin, text_end));

  GtkTextIter range_begin;
  gtk_text_buffer_get_iter_at_offset(gobj(), &range_begin, start_offset);

  const auto tag_table = gtk_text_buffer_get_tag_table(gobj());
  Glib::ArrayHandler<Glib::ustring>::ArrayKeeperType array_keeper (Glib::ArrayHandler<Glib::ustring>::vector_to_array(tag_names));

  const char *const *const names_begin = array_keeper.data();
  const char *const *const names_end   = names_begin + tag_names.size();

  for(const char *const * pname = names_begin; pname != names_end; ++pname)
  {
    if(GtkTextTag *const tag = gtk_text_tag_table_lookup(tag_table, *pname))
    {
      gtk_text_buffer_apply_tag(gobj(), tag, &range_begin, range_end.gobj());
    }
    else
    {
      g_warning("Gtk::TextBuffer::insert_with_tags_by_name(): no tag with name '%s'!", *pname);
    }
  }

  return range_end;
}

TextBuffer::iterator TextBuffer::insert_markup(const iterator& pos, const Glib::ustring& markup)
{
  // gtk_text_buffer_insert_markup() modifies the iterator, but that's not the
  // STL way so we give it something that we don't mind it modifying.
  iterator iterCopy (pos);
  gtk_text_buffer_insert_markup(gobj(), iterCopy.gobj(), markup.data(), markup.bytes());

  // According to the gtk_text_buffer_insert_markup() docs, the "default signal handler
  // revalidates it to point to the end of the inserted text".
  return iterCopy;
}

TextBuffer::iterator TextBuffer::insert_markup(const iterator& pos, const char* markup_begin, const char* markup_end)
{
  // gtk_text_buffer_insert_markup() modifies the iterator, but that's not the
  // STL way so we give it something that we don't mind it modifying.
  iterator iterCopy (pos);
  gtk_text_buffer_insert_markup(gobj(), iterCopy.gobj(), markup_begin, markup_end - markup_begin);

  // According to the gtk_text_buffer_insert_markup() docs, the "default signal handler
  // revalidates it to point to the end of the inserted text".
  return iterCopy;
}

TextBuffer::iterator TextBuffer::insert(const iterator& pos,
                                        const const_iterator& range_begin, const const_iterator& range_end)
{
  iterator iterCopy (pos);
  gtk_text_buffer_insert_range(gobj(), iterCopy.gobj(), range_begin.gobj(), range_end.gobj());
  return iterCopy;
}

std::pair<TextBuffer::iterator,bool>
TextBuffer::insert_interactive(const iterator& pos, const const_iterator& range_begin,
                               const const_iterator& range_end, bool default_editable)
{
  // Since we have to copy the iterator anyway we can as well create the
  // std::pair now.  That saves another copy later (mind you, TextIter is
  // a heavy struct), and allows modern compilers to apply the return value
  // optimization.
  std::pair<iterator,bool> pair_iter_success (pos, false);

  pair_iter_success.second = gtk_text_buffer_insert_range_interactive(
      gobj(), pair_iter_success.first.gobj(), range_begin.gobj(), range_end.gobj(), default_editable);

  return pair_iter_success;
}

TextBuffer::iterator TextBuffer::erase(const iterator& range_begin, const iterator& range_end)
{
  // GTK+ sets the iterators to where the deletion occured. We do it the STL way and therefore need copies.
  iterator beginCopy (range_begin);
  iterator endCopy   (range_end);
  gtk_text_buffer_delete(gobj(), beginCopy.gobj(), endCopy.gobj());
  return beginCopy;
}

TextBuffer::iterator TextBuffer::backspace(const iterator& iter, bool interactive, bool default_editable)
{
  // GTK+ sets the iterators to where the deletion occured. We do it the STL way and therefore need copies.
  iterator copy(iter);
  gtk_text_buffer_backspace(gobj(), copy.gobj(), interactive, default_editable);
  return copy;
}

_IGNORE(gtk_text_buffer_backspace)

std::pair<TextBuffer::iterator,bool>
TextBuffer::erase_interactive(const iterator& range_begin, const iterator& range_end,
                              bool default_editable)
{
  // Since we have to copy the iterator anyway we can as well create the
  // std::pair now.  That saves another copy later (mind you, TextIter is
  // a heavy struct), and allows modern compilers to apply the return value
  // optimization.
  std::pair<iterator,bool> pair_iter_success (range_begin, false);

  // GTK+ sets the iterators to where the deletion occured.
  // We do it the STL way and therefore need copies.
  iterator endCopy (range_end);

  pair_iter_success.second = gtk_text_buffer_delete_interactive(
      gobj(), pair_iter_success.first.gobj(), endCopy.gobj(), default_editable);

  return pair_iter_success;
}

TextBuffer::iterator TextBuffer::get_iter_at_child_anchor(const Glib::RefPtr<ChildAnchor>& anchor)
{
  iterator iter;
  gtk_text_buffer_get_iter_at_child_anchor(gobj(), iter.gobj(), anchor->gobj());
  return iter;
}

TextBuffer::const_iterator TextBuffer::get_iter_at_child_anchor(const Glib::RefPtr<ChildAnchor>& anchor) const
{
  return const_cast<TextBuffer*>(this)->get_iter_at_child_anchor(anchor);
}

int TextBuffer::size() const
{
  return get_char_count();
}

Glib::ustring TextBuffer::get_text(bool include_hidden_chars) const
{
  auto unconst = const_cast<TextBuffer*>(this); //Because begin() and end() are not const.
  return get_text(unconst->begin(), unconst->end(), include_hidden_chars);
}

guint TextBuffer::add_commit_notify(NotifyFlags flags, const SlotCommitNotify& 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_CommitNotify_gtk_callback_destroy() is called.
  auto slot_copy = new SlotCommitNotify(slot);

  return gtk_text_buffer_add_commit_notify(gobj(),
    static_cast<GtkTextBufferNotifyFlags>(flags),
    &SignalProxy_CommitNotify_gtk_callback, slot_copy,
    &SignalProxy_CommitNotify_gtk_callback_destroy);
}

} // namespace Gtk
