module WorkFlowHelper

  def get_input_html(name, value, write_type=true)
    html = ""
    javascript = ""
    if Array === value
      ary = get_input_html(name+[0], value[0])
      fname = "add_#{name.join("_")}"
      html += "["
      html += ary[0]
      html += ", "
      html += "<span class=\"link\" onclick=\"#{fname}(this);\">add</span>"
      html += "]"
      if ary[1]
        javascript += ary[1]
      end
      tmp = "tmp#{name.length}"
      ary = get_input_html(name+[tmp], value[0], false)
      javascript +=<<"EOF"
window.#{fname} = function(elm) {
  if (elm.count)
    elm.count += 1;
  else
    elm.count = 1;
  new Insertion.Before(elm,'#{ary[0]}, '.gsub('#{tmp}',elm.count));
EOF
      if ary[1]
        javascript += "  eval('#{escape_javascript(ary[1])}'.gsub('#{tmp}',elm.count));\n"
      end
    javascript += "}\n"
    elsif Hash === value
      html += '<ul style="margin:0">'
      value.each{|k,v|
        ary = get_input_html(name+[k], v)
        html += "<li>#{k}: "
        html += ary[0]
        if ary[1]
          javascript += ary[1]
        end
      }
      html += '</ul>'
    elsif value == "string"
      if write_type
        html += "(#{value})"
      end
      html += text_field_tag("apis[api_id][#{name.join("][")}]")
    elsif value == "int" || value == "float" || value == "double"
      if write_type
        html += "(#{value})"
      end
      html += text_field_tag("apis[api_id][#{name.join("][")}]", nil, :size=>5)
    elsif value == "boolean"
      html += select_tag("apis[api_id][#{name.join("][")}]", "<option></option><option>true</option><option>false</option>")
    elsif
      if write_type
        html += "(#{value})"
      end
      html += text_field_tag("apis[api_id][#{name.join("][")}]")
    end
    return html, javascript=="" ? nil : javascript
  end

  def get_output_text(value, type, name="")
    if Array === value
      case type
      when "html"
        return "[#{get_output_text(value[0], type)}]"
      when "list"
        ary = Array.new
        3.times{|i|
          ary[i] = get_output_text(value[0], type, name+"[#{i}]")
        }
        return ary.join(",")
      end
    elsif Hash === value
      case type
      when "html"
        return "{#{value.collect{|k,v| k+"=>"+get_output_text(v,type)}.join(", ")}}"
      when "list"
        return value.collect{|k,v| get_output_text(v,type,name+"[#{k}]")}.join(", ")
      end
    else
      case type
      when "html"
        return "(#{value})"
      when "list"
        return "'(#{value})#{name}'"
      end
    end
  end

end
