#!/usr/bin/ruby -w
# Encoding: UTF-8
# frozen_string_literal: true
# =========================================================================== #
require 'gtk2'

alias e puts

label = Gtk::Label.new

Thread.new {
  (0 ... 1000).each { |cnt|
    e 'A:' + cnt.to_s
    label.label = 'A:' + cnt.to_s
    sleep(2)
  }
}

start_button = Gtk::Button.new('start Thread B (Thread A is continuously running already --- see above ^^^)')
stop_button  = Gtk::Button.new('stop Thread B')
  
stop_button.signal_connect(:clicked) {
  if @th
    @th.kill
    puts 'Killed Thread B'
    @th = nil
    start_button.sensitive = true
    start_button.grab_focus
    stop_button.sensitive = false
  end
}

stop_button.sensitive = false
@box = Gtk::VBox.new
@buffer = Gtk::TextBuffer.new
textview = Gtk::TextView.new(@buffer)

@box << label << start_button << stop_button << textview

start_button.signal_connect(:clicked) {
  start_button.sensitive = false
  @th = Thread.new {
    (0...10).each { |cnt|
      e 'B:'+cnt.to_s
      label.label = 'B:'+cnt.to_s
      set_text 'Hi '+rand(25).to_s
      sleep(2)
    }
    @th = nil
    start_button.sensitive = true
    start_button.grab_focus
    stop_button.sensitive = false
  }
  stop_button.sensitive = true
  stop_button.grab_focus
}

# =========================================================================== #
# === set_text
# =========================================================================== #
def set_text(i)
  @buffer.set_text(i)
end

if __FILE__ == $PROGRAM_NAME
  window = Gtk::Window.new
  window.add(@box)
  window.show_all
  window.move(0, 0)
  window.set_size_request(800, 200)
  Gtk.main
end