#!/usr/bin/env ruby

# Copyright 2004 Leslie A. Hensley
# hensleyl@papermountain.org
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program 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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

require 'Borges'
require 'Borges/WEBrick'

class Borges::HtmlAttributes
  alias_method :old_array_equals, :[]=
  def [] attr
    self[attr]=attr
  end

  def []= attr, value
    @attribute_values ||= {}
    @attribute_values[attr] = value
    old_array_equals(attr, value)
  end

  def get_value attr
    @attribute_values ||= {}
    @attribute_values[attr]
  end
end

class Borges::HtmlBuilder
  def inline_script(str)
    attributes[:type] = 'text/javascript'
    tag_do 'script', str
  end
   
  def script_with_url(urlString)
    attributes[:type] = 'text/javascript'
    attributes.src(urlString)
    head_tag('script')
  end
end

class Borges::HtmlRenderer
  alias_method :old_initialize, :initialize
  
  def initialize rendering_context
    @id_counter = 0
    old_initialize rendering_context
  end
    
  def next_id
    @id_counter += 1
    "id-#{@id_counter}"
  end
  
  def ensure_id
    element_id next_id unless attributes.get_value :id
    attributes.get_value :id
  end
  
  def text_input_with_callback block, &live_block
    id = ensure_id
    text_input &block
    uri = Borges::Session.current_session.application.url_for_request_handler(LiveRequestHandler.new(self, &live_block))
    inline_script("liveSearch('#{id}', '#{uri}')")
  end
end

class LiveRequestHandler < Borges::RequestHandler
  def initialize(html, &block)
    @html = html
    @block = block
  end
  
  def handle_request req
    text = req.fields['s']
    response = Borges::HtmlResponse.new
    renderer = Borges::HtmlRenderer.new(@html.rendering_context.dup)
    renderer.document = response
    @block.call(renderer, text)
    response
  end

  def active?
   true
  end
end

class UpdateTest < Borges::Component
  def render_content_on r
    r.script_with_url('/static/liveUpdater.js')
    r.paragraph "Type the first few letters of a word in the text field and pause for a second."
    r.form do
      r.text_input_with_callback(proc {}) do |r2, text|
        if text.length > 1
          r2.div_named 'bar', `grep -i \"^#{text}\" /usr/share/dict/words`.gsub("\n", "<br/>")
        end
      end
      r.div_named 'bar', ''
    end
  end
  
  register_application('live')
end

options = {}
options[:Port] ||= 8080
server = WEBrick::HTTPServer.new(options)
server.mount("/static", WEBrick::HTTPServlet::FileHandler, "static")
server.mount("/borges", Borges::WEBrickServlet)
trap('INT'){ server.shutdown }
server.start