require 'time'

#
# == Synopsis
#
# CookieCollection should be utilized by clients that need HTTP cookie
# management. This class assists in storing and parsing raw cookies and
# returning non-expired cookies for the cookie's originating server.
#
# *NOTE* This class is largely unimplemented and only stores and returns a
# single raw cookie header without any processing or domain discretion.
#
# == Implementation Notes
#
# * RFC 2109, version 1 cookies (http://tools.ietf.org/html/rfc2109)
# * Uses Netscapes' "Expires" instead of RFC's "Max-Age" attribute. Expires is
#   an RFC 2822 date. 
#
#--
# TODO Fully implement this class.
#++
# 
class CookieCollection

  #--
  # XXX do we want to accept CGI::Cookie or raw cookie strings and convert to CGI::Cookie?
  #++
  def initialize
    @cookies = nil
  end

  #--
  # Need to parse set-cookie response string and instantiate a CGI::Cookie for
  # each and store in +@cookies+.
  #
  # Example of 2 cookies returned by WEBrick:
  #
  # "VAL1=Data1; Version=1; Expires=Sat, 11 Oct 2008 11:17:54 GMT, VAL2=Data2; Max-Age=3600"
  #++
  def store cookie
    @cookies = cookie
  end

  def clear
    @cookies = nil
  end

  #--
  # Don't return expired cookies.
  # Commas seperate cookie values.
  # Only compile cookies that have applicable domain and path.
  # Cookie data needs to be ordered by path.
  # 
  # Cookie header to send in an HTTP request to the originating server.
  #
  # Cookie Header Syntax:
  #   cookie          =    "Cookie:" cookie-version
  #                        1*((";" | ",") cookie-value)
  #   cookie-value    =    NAME "=" VALUE [";" path] [";" domain]
  #   cookie-version  =    "$Version" "=" value
  #   NAME            =    attr
  #   VALUE           =    value
  #   path            =    "$Path" "=" value
  #   domain          =    "$Domain" "=" value
  #
  # Cookie Header Example:
  #
  #   $Version=1; Val1="data1"; $Path="/dir"; Val2="data2"; $Path="/"
  #++
  def cookie_header_data domain, path
    @cookies
    #@cookies.collect do |cookie|
    #  next  if Time.rfc2822(cookie.expires) < Time.now 
    #  next  if cookie.domain != domain
    #  next  if cookie.path !~ /^#{path}/

    #  "Cookie: #{cookie}"  if cookie.domain == domain
    #end
  end

  def cookie_header domain, path
    "Cookie: " + cookie_header_data(domain, path)
  end

end
