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

module Qwik
  class Action
    def plg_hcomment(style="0")
      style = style.to_i
      style = 0 if style != 1
      # @hcomment_num is global for the Action
      @hcomment_num = 0 if !defined?(@hcomment_num)
      @hcomment_num += 1
      [:div, {:class=>"hcomment"},
	[:form, {:method=>"POST", :action=>@req.base+".hcomment"},
	  _("Name"), ": ", [:input, {:name=>"name", :size=>10}],
	  " ", _("Comment"), ": ", [:input, {:name=>"msg", :size=>50}], " ",
	  [:input, {:type=>"submit", :name=>"comment", :value=>_("Submit")}],
	  [:input, {:type=>"hidden", :name=>"comment_no", :value=>@hcomment_num}],
	  [:input, {:type=>"hidden", :name=>"style", :value=>style}]]]
    end

    def ext_hcomment
      #c_require_login
      c_require_post

      date = Time.now.format_date
      user = @req.query["name"]
      hcomment_noname = _("Anonymnous")
      user = hcomment_noname if user.nil? || user == ""
      msg = @req.query["msg"]
      raise "no message" if msg.nil? || msg == ""
      comment_no = @req.query["comment_no"].to_i
      comment_no = 1 if comment_no < 1
      style = @req.query["style"].to_i
      style = 0 if style != 1

      content = "-#{date} ''[[#{user}]]'' : #{msg}\n"
      page = @site[@req.base]

      str = page.load
      md5 = str.md5hex
      nstr = ""
      num = 1
      written = false
      str.each {|line|
	if /^\{\{hcomment/ =~ line && !written
	  if num == comment_no
	    nstr << content if style == 0 # new comment is on the bottom.
	    nstr << line
	    nstr << content if style == 1 # new comment is on the top.
	    written = true
	  else
	    nstr << line
	    num += 1
	  end
	else
	  nstr << line
	end
      }

      if !written
	return c_nerror(_("Failed to add a comment.")){
	  _("Failed to add a comment.")
	}
      end

      page.store(nstr, md5)

      c_make_log("hcomment") # COMMENT
      c_monitor("hcomment") # COMMENT
      url = @req.base+".html"
      return c_notice(_("Add a comment."), url){[
	  _("Message is added."),
	  [:hr],
	  [:p,_("Go next")," : ",[:a,{:href=>url},url]],
	]}
    end
  end
end

if $0 == __FILE__
  $LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
  require "t/test"
  $debug = true
end

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

    def test_hcomment
      t_add_user

      page = @site.create_new
      page.store("{{hcomment}}\n")
      session("/test/1.html")
      assert_attr({"action"=>"1.hcomment", "method"=>"POST"}, "form")
      assert_attr({"name"=>"name", "size"=>"10"}, "input")

      session("POST /test/1.hcomment?name=n&msg=m&comment_no=1&style=0")
      assert_match(/ ''\[\[n\]\]'' : m\n\{\{hcomment\}\}/, page.load)

      page.store("{{hcomment(1)}}\n")
      session("POST /test/1.hcomment?name=n&msg=m&comment_no=1&style=1")
      assert_match(/\{\{hcomment\(1\)\}\}\n\-/, page.load)
    end
  end
end
