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

module WebUnit

  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|
        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
      # 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
        data << p.query_data
      end
      raise ElemNotFound if button != nil && matched == nil
      Response::new.init_http( @action, @method, data.compact.join('&') )
    end

  end

end
