=begin
= WebUnit::Form
  Copyright(C) 2001 yuichi TAKAHASHI, Narushima Hironori.
  $Id: form.rb,v 1.1.1.1 2003/01/21 11:50:40 yuichi Exp $
=end
module WebUnit

  BOUNDARY = '--divider'

  class Form < HtmlElem

    attr_accessor :name, :action, :method, :encoding
    attr_reader :parameters, :params

    def initialize( ah )
      super( 'form', ah )
      @parameters = []    # index by int
      @params = {}        # index by name
      @action = ah["name"]
      @action = ah["action"]
      @method = ah["method"] == nil ? "GET" : ah["method"]
      #print @action,":",method,"\n"
    end

    def add_param( param )
      @parameters.push param
      if @params.key?param.name then
        @params[param.name].update( param )
        param.update( @params[param.name] )
      else
        @params[param.name] = param
      end
    end

    def freeze
      @parameters.freeze
      @params.freeze
    end

=begin
--- Form#set_params( hash )
      fill up each fields, by name.
=end

    def set_params( hash )
      hash.each do |k,v|
        raise ArgumentError.new("wrong key: " + k) unless self.params[k]
        self.params[k].value = v
      end
      self
    end

=begin
--- Form#set_parameters( array )
      fill up each fields, by index.
=end

    def set_parameters( array )
      array.each_index do |i|
        self.parameters[i].value = array[i]
      end
      self
    end

=begin
--- Form#store_test_data(fields,data,s=',',button=nil)
      store data to backend ( Database, File, ... ).
      input csv data to each fields, and submit.
=end

    def store_test_data( fields, data, s=',', button=nil )
      data.split( "\n" ).collect{ |r| r.strip.split( s ) }.each do |r|
        fields.each_index{ |i| @params[fields[i]].value = r[i] }
        self.submit( button )
      end
    end

=begin
--- Form#submit(button=nil,x=nil,y=nil)
      submit form, and return a Response.
=end
    def submit( button=nil, x=nil, y=nil )
      data = []
      matched = nil
      multipart = (attrs['enctype'] == 'multipart/form-data')
      # make data from params

      @parameters.each do |p|
        puts "#{p.class}/#{p.name}" if $DEBUG
        if p.class == InputSubmit || p.class == InputImage
          next unless p.name == button || p.value == button
          matched = p
          if p.class  == InputImage
            p.x = x
            p.y = y
          end
        end
        
        if multipart
          data << p.multipart_query_data(BOUNDARY)
          else
          data << p.query_data
        end
      end
      
      if multipart
        data = data.join('') + "--#{BOUNDARY}--\n"
      else
        data = data.compact.join('&')
      end
    
      Response::new.init_http( @action, @method, data, false, multipart)
    end
  end

end
