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

require "resolv"
$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/config"

module Qwik
  class AccessLog
    def initialize(config, log_file)
      @config = config
      @log = log_file # IO?
      @log = open(log_file, "ab+") if log_file.is_a? String
      @log.sync = true
    end

    def close
      @log.close
      @log = nil
    end

    def resolve(ip)
      begin
	return Resolv.getname(ip).to_s
      rescue
	return ip
      end
    end

    def format_log_line(req, response)
      time     = req.start_time.rfc_date
      fromhost = req.fromhost
      user     = req.user || "-"
      request_line = req.request_line
      status   = response.status
      len      = "-"
      len      = response.body.length if response.body.is_a? String
      "#{time} #{fromhost} #{user} \"#{request_line}\" #{status} #{len}\n"
    end

    IGNORE_ACTION = ["theme"]
    def log(request, response, req, res)
      return if IGNORE_ACTION.include?(req.plugin)
      format = format_log_line(req, response)
      @log << format
      $stdout << format if @config.debug &&  !@config.test
    end
  end
end

if $0 == __FILE__
  require "test/unit"
  require "qwik/qp"
  require "qwik/wabisabi.rb"
  require "qwik/util-path"
  $debug = true
end

if $debug
  class TC_Logger < Test::Unit::TestCase
    def test_logger
      config = Qwik::Config.new(true)
      path = "test-logger.txt".path
      path.unlink if path.exist?
      assert_equal(false, path.exist?)
      logger = Qwik::AccessLog.new(config, path.to_s)
      assert_equal(true, path.exist?)
      #logger.log
      logger.close
      path.unlink if path.exist?
      assert_equal(false, path.exist?)
    end
  end
end
