#!/usr/bin/ruby
# Text example — scrollable text viewer with word/row picking
#
# Usage:
#   cd example && ruby text e.txt
#   cat somefile.txt | ruby text
#
# Reads from a file argument or stdin, displays it in a
# word-wrapped scrollable viewport with a border.
#
# Keys:
#   /         Search (type pattern, Enter to run)
#   n         Next match
#   p         Previous match
#   arrows    Scroll up/down
#   w         Pick a single word (hint-driven)
#   W         Pick multiple words
#   r         Pick a single row
#   R         Pick multiple rows
#   esc       Exit
#
# The text is word-wrapped to fit the viewport width.
# Header shows above the content area; hints mark
# selectable words/rows for picking.

require_relative '../lib/typr.rb'

class TextTest
  # extend Typr
  include Typr
  # Typr.frontend :terminal
  def initialize
    Typr.init 
    @text = Text.new( 
      input: $<, header: "Text Area Header",
      top: 2, left: 0.1, right: 0.9, bottom: -4, 
      border: :round, borders:{ left: ?┆, right: ?┆, top: ?╌, bottom: ?╌ },
      colors: { header: [:yellow, :grey30], hints: [:black, :white] }
    )
    @user = Line.new( top: -1, 
      default: "[/]:search [n]ext [p]rev, pick [r]ow/[R]ows, [w]ord/[W]ords, [esc] quit",
      colors: { question: :blue, answer: :yellow } )
  end
  
  def run
    Typr.clear
    loop do
      @text.show 
      @user.show
      case key = Typr.read( :key )
        when KEY_ESCAPE; exit
        when ?/; @text.search
        when ?w; @user.ask( 'pick word':  [@text, :field] )
        when ?W; @user.ask( 'pick words': [@text, :fields] )
        when ?r; @user.ask( 'pick rows': [@text, :row] )
        when ?R; @user.ask( 'pick rows': [@text, :rows] )
        else; @text.send key; @user.reset
      end
    end
  end
end

begin 
  TextTest.new.run
ensure 
  Typr.exit
end

