#!/usr/bin/ruby -w
# Encoding: UTF-8
# frozen_string_literal: true
# =========================================================================== #
# require 'text_iterator_example.rb'
# =========================================================================== #
require 'gtk3'

class AppWindow < ::Gtk::Box

  # ========================================================================= #
  # === initialize
  # ========================================================================= #
  def initialize(
      run_already = true
    )
    super(:horizontal, 2)
    set_border_width(15)
    set_size_request(500, 500)
    reset
    run if run_already
  end

  # ========================================================================= #
  # === reset
  # ========================================================================= #
  def reset
    @textview = Gtk::TextView.new
  end

  # ========================================================================= #
  # === on_insert_text
  #
  # This method will insert the given text, at the given position.
  # ========================================================================= #
  def on_insert_text(button, w)
    buffer = w.buffer
    text = buffer.text.to_s
    mark = buffer.get_mark(text)
    iter = buffer.get_iter_at_mark(mark)
    buffer.insert(iter, text, text.size)
  end

  # ========================================================================= #
  # === on_retrive_text
  # ========================================================================= #
  def on_retrieve_text(button, text_view)
    buffer = text_view.buffer
    start_position, end_position = buffer.selection_bounds # Returns: [start, end, selected] 
    text = buffer.get_text(start_position, end_position, false)
    print(text)
  end

  # ========================================================================= #
  # === run
  # ========================================================================= #
  def run
    entry = Gtk::Entry.new
    retrieve = Gtk::Button.new(label: 'Get Text')
    insert_button = Gtk::Button.new(label: 'Insert Text')
    insert_button.signal_connect(:clicked) {
      on_insert_text(entry, @textview)
    }
    retrieve.signal_connect(:clicked) {
      on_retrieve_text(entry, @textview)
    }
    scrolled_win = Gtk::ScrolledWindow.new
    scrolled_win.add(@textview)
    hbox = Gtk::Box.new(:horizontal, 5)
    hbox.pack_start(entry, fill: true, expand: true, padding: 0)
    hbox.pack_start(insert_button, fill: true, expand: true, padding: 0)
    hbox.pack_start(retrieve, fill: true, expand: true, padding: 0)
    vbox = Gtk::Box.new(:vertical, 5)
    vbox.pack_start(scrolled_win, fill: true, expand: true, padding: 0)
    vbox.pack_start(hbox, fill: true, expand: true, padding: 0)
    add(vbox)
    show_all
  end

end

if __FILE__ == $PROGRAM_NAME
  window = Gtk::Window.new
  window.add(AppWindow.new)
  window.show_all
  window.move(0, 0)
  Gtk.main
end