=begin
= WebUnit::Cookies
  Copyright(C) 2001 yuichi TAKAHASHI
  $Id: cookie.rb,v 1.1.1.1 2002/03/29 15:13:21 yuichi Exp $
=end

require 'singleton'

module WebUnit

  class Cookies

    include Singleton

    def initialize
      @cookies = {}
    end

=begin
--- Cookies.clear
=end

    def self::clear
      self::instance.clear
    end

    def clear
      @cookies = {}
    end

=begin
--- Cookies.add( name, value, path )
=end

    def self::add( n, v, p='/' )
      self::instance.add( n, v, p )
    end

    def add( n, v, p )
      h = {}
      h["name"] = n
      h["value"] = v
      @cookies[[n,p]] = h
    end

=begin
--- Cookies.list
=end

    def self::list
      self::instance.list
    end

    def list
      @cookies.keys.collect{|x|x[0]}
    end

=begin
--- Cookies.has?
=end

    def self::has?( name )
      self::instance.has?( name )
    end

    def has?( name )
      @cookies.keys.collect{|x|x[0]}.include?( name )
    end

    def self::update( set_cookie_response )
      self::instance.update( set_cookie_response )
    end

    def update( set_cookie_response )
      if set_cookie_response != nil then
        set_cookie_response.split(',').each do |e|
          c = parse_cookie( e.strip )
          @cookies[ [ c["name"], c["path"] ] ] = c
        end
      end
    end

    def self::header( target )
      self::instance.header( target )
    end

    def header( target )
      a = []
      @cookies.keys.each do |name,path|
        if path == nil || ( 'path=' + target ).index( path ) != nil then
          a.push( name + '=' + @cookies[[name,path]]["value"] )
        end
      end
      a.size == 0 ? {} : { "Cookie"=>( a.join( '; ' ) ) }
    end

    attr_reader :cookies

    def cookies= ( hash )
      raise ArgumentError unless hash.kind_of?( Hash )
      @cookies = hash
    end

    private

    def parse_cookie( line )
      h = {}
      attrs = line.split(';').collect{ |x| x.strip.split('=') }
      h["name"], h["value"] = attrs.shift
      attrs.each do |arr|
        h[arr[0]] = arr[1]
      end
      h
    end

  end

end
