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

module Qwik
  class Action
    def c_time_str
      time = @req.start_time
      return sprintf("%.6f", time.to_i + time.usec/1000000.0)
    end

    def c_make_log(cmd, pagename=@req.base)
      timestr = c_time_str
      @site.log(timestr, @req.user, cmd, pagename)
    end

    def plg_sitelog # sitelog viewer
      e = []
      @site.sitelog.list.each {|k, v|
	user, cmd, pagename = v
	user = "anonymous" if user.nil? || user == ""
	user = MailAddress.new(user).obfuscate if user != ""
	e << [:dt, Time.at(k.to_i).ymdx+" - "+user]
	e << [:dd, cmd+": ", [:a, {:href=>pagename+".html"}, pagename]]
      }
      [:dl, *e]
    end

    def act_sitelog # sitelog viewer
      return sitelog_viewer
    end

    def sitelog_viewer
      return c_plain("SiteLog"){
	[:div, {:class=>"day"},
	  [:div, {:class=>"section"},
	    plg_sitelog]]
      }
    end

  end
end

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

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

    def test_time_str
      session
      assert_match(/\d+\.\d{6}/, @action.c_time_str)
    end

    def test_sitelog
      t_add_user

      # Create a page.
      session("POST /test/.new?t=TestPage"){|req|
	req.start_time += 1
      }
      assert_match(/,user@e.com,create,TestPage\n/,
		   @site["_SiteLog"].load)

      # Save a page.
      session("POST /test/TestPage.save?contents=t"){|req|
	req.start_time += 2
      }
      assert_match(/,user@e.com,save,TestPage\n/, @site["_SiteLog"].load)

      # Delete a page.
      session("POST /test/TestPage.save?contents="){|req| # null content
	req.start_time += 3
      }
      assert_match(/,user@e.com,create,TestPage\n/,
	   @site["_SiteLog"].load)
      assert_match(/,user@e.com,save,TestPage\n/, @site["_SiteLog"].load)
      assert_match(/,user@e.com,delete,TestPage\n/,
		   @site["_SiteLog"].load)

      # See the SiteLog.
      page = @site.create_new
      page.store("{{sitelog}}")
      session("/test/1.html"){|req|
	req.start_time += 4
      }
      div = @res.body.get_path("//div[@class='section']")
      div = div.inside.remove_comment.get_single
      assert_equal([:dd, "create: ",
		     [:a, {:href=>"TestPage.html"}, "TestPage"]], div[2])
      assert_equal([:dd, "save: ",
		     [:a, {:href=>"TestPage.html"}, "TestPage"]], div[4])
      assert_equal([:dd, "delete: ",
		     [:a, {:href=>"TestPage.html"}, "TestPage"]], div[6])
    end
  end
end
