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

$LOAD_PATH.unshift("../../compat") unless $LOAD_PATH.include?("../../compat")
#require "webrick"
require "webrick/httpstatus"
$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/act-files"

module Qwik
  class Action
    def c_simple_send(path, type)
      ss = SimpleSender.new(@config, @req, @res)
      ss.simple_send(path.to_s, type)
    end
  end

  class SimpleSender
    def initialize(config, req, res)
      @config, @req, @res = config, req, res
    end

    # copied from webrick
    def simple_send(local_path, mtype)
      #raise WEBrick::HTTPStatus::NotFoundError if !local_path.path.exist?
      raise WEBrick::HTTPStatus::NotFound if !local_path.path.exist?
      st = local_path.path.stat
      mtime = st.mtime
      @res["etag"] = sprintf("%x-%x-%x", st.ino, st.size, st.mtime.to_i)
      if not_modified?(mtime)
	@res.body = ""
	raise WEBrick::HTTPStatus::NotModified
      else
	@res["Content-Type"]   = mtype
	@res["Content-Length"] = st.size
#	presen = true
	presen = false
	if !presen # do not use Last-Modified in presentation...
	  @res["Last-Modified"]  = mtime.httpdate
	end
	if @config.ssl # bad knowhow
	  # BUG: ssl can not send data as stream.
	  @res.body = open(local_path, "rb"){|f| f.read}
	else
	  @res.body = open(local_path, "rb")
	end
      end
    end

    def not_modified?(mtime)
      if ir = @req["if-range"]
	begin
	  return true if ::Time.httpdate(ir) >= mtime
	rescue
	  return true if WEBrick::HTTPUtils::split_header_valie(ir).member?(@res["etag"])
	end
      end

      return true if (ims = @req["if-modified-since"]) &&
	::Time.parse(ims) >= mtime

      return true if (inm = @req["if-none-match"]) &&
	WEBrick::HTTPUtils::split_header_value(inm).member?(@res["etag"])

      false
    end
  end
end

if $0 == __FILE__
  require "t/test"
  require "qwik/act-attach"
  $debug = true
end

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

    def test_simple_send
      t_add_user

      page = @site.create_new
      page.store("t")

      content = WEBrick::HTTPUtils::FormData.new("test\n")
      content.filename = "t.txt"
      session("POST /test/1.files") {|req|
	req.query.update({"content"=>content})
      }
      assert_text("Attach file done", "title")

      session("/test/1.files/t.txt")
      assert_instance_of(File, @res.body)
      str = @res.body.read
      @res.body.close # important
      assert_equal("test\n", str)
      assert_equal("text/plain", @res["Content-Type"])
    end
  end
end
