# Copyright (C) 2003-2005 Kouichirou Eto, All rights reserved.

$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/act-plain"

module Qwik
  class Action
    def plg_search_form
      [:form, {:action=>".search"},
	[:input, {:name=>"q"}],
	[:input, {:type=>"submit", :value=>_("Search")}]]
    end

    def act_search
      key = @req.query["q"]
      if key.nil? || key == ""
	return search_form_page
      end

      ar = []
      @site.each {|page|
	str = page.load
	str.each_with_index {|line, i|
	  if line.include?(key) # do not use Regexp for now by security reason.
	    ar << [page, line, i]
	  end
	}
      }

      if ar.length == 0
	return c_notice(_("Search result")){
	  _("No match.")
	}
      end

      return search_result(ar)
    end

    def search_form_page
      c_notice(_("Search")){
	[:div, {:class=>"form"},
	  plg_search_form]
      }
    end

    def search_result(ar)
      ul = ar.map {|page, line, i|
	[:li, [:a, {:href=>page.url}, page.key],
	  " : "+i.to_s+" : "+line]
      }
      return c_plain(_("Search result")){
	[:div, {:class=>"day"},
	  [:div, {:class=>"section"},
	    [:ul, *ul]]]
      }
    end


  end
end

if $0 == __FILE__
  require "t/test"
  $debug = true
end

if $debug
  class TC_ActSearch < Test::Unit::TestCase
    include TestSession

    def test_search
      t_add_user

      # test_plg_search_form
      assert_wiki([:form, {:action=>".search"},
		    [:input, {:name=>"q"}],
		    [:input, {:value=>"Search", :type=>"submit"}]],
		  "{{search_form}}")
      @site["1"].delete

      # test_act_search
      session("/test/.search")
      assert_attr({"action"=>".search"}, "form")
      assert_attr({"name"=>"q"}, "input")

      session("/test/.search?q=nosuchkey")
      assert_text("Search result", "h1")
      assert_in(["No match."], "//div[@class='section']")

      page = @site.create_new
      page.store("This is a keyword.")
      session("/test/.search?q=keyword")
      assert_xml([:ul, [:li, [:a, {:href=>"1.html"}, "1"],
		     " : 0 : This is a keyword."]],
		 "//div[@class='section']")

      page = @site.create_new
      page.store("Š¿Žš")
      session("/test/.search?q=Žš")
      assert_xml([:ul, [:li, [:a, {:href=>"2.html"}, "2"],
		     " : 0 : Š¿Žš"]],
		 "//div[@class='section']")
    end
  end
end
