# $Id: ext_sitelog.rb,v 1.5 2004/05/12 10:42:27 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require 'qwik/ext_wikidb'

module Qwik
  class Site
    def log(time, user, cmd, pagename)
#      now = Time.now
#      t = (now.to_i + now.usec/1000000.0).to_s
      #qp t, now.to_i, now.usec
      sitelog.add(time, user, cmd, pagename)
    end

    def sitelog()
      @sitelog = SiteLog.new(@config, self) if @sitelog.nil?
      @sitelog
    end
  end

  class SiteLog
    KEY = "_SiteLog" # pagename begin with _ will not be shown in the list.
    def initialize(config, site)
      @config = config
      @site = site
      @key = KEY
    end

    def add(t, user, cmd, pagename)
      db.add(t, user, cmd, pagename)
    end

    def list
      db.hash.sort
    end

    private
    def db
      page = @site[@key]
      page = @site.create(@key) if page.nil?
      page.wikidb
    end
  end

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