#! /usr/bin/env ruby
require File.dirname(__FILE__) + '/lib/base'

class RoboFormImporter < Importer

  def process_contents(contents)
    s = contents.gsub('<WBR>', "").gsub("&amp;", "&").gsub("&lt;", "<").gsub("&gt;", ">").gsub("&nbsp;", " ").gsub("&apos;", "'").gsub("&quot;", '"')
    
    items = s.split("<TBODY>")
    for item in items do
      process_item(item)
    end
  end
  
  def process_item(s)
    name = nil
    if s =~ /TD class=caption[^>]+>([^<]+)<(.*)/im
      name = $1
      s = $2
    end
    
    url = nil
    if s =~ /TD class=subcaption[^>]+>([^<]+)<(.*)/im
      url = $1
      s = $2
    end

    return if name.nil? || url.nil?

    webform = WebForm.new
    webform.title = name
    webform.url = url

    while true
      field = nil
      if s =~ /TD class=field[^>]+>([^<]+)<(.*)/im
        field = $1
        s = $2
      else
        break
      end
      
      value = nil
      if s =~ /TD class=wordbreakfield[^>]+>([^<]+)<(.*)/im
        value = $1
        s = $2
      else
        break
      end
      
      if field == "User ID$"
        webform.add_username(value)
      elsif field == "Password$"
        webform.add_password(value)
      elsif field =~ /passw/i || field =~ /pw/i
        webform.add_field(field, value, "P")
      else
        webform.add_field(field, value)
      end
    end
    
    add_item(webform)
  end
end

RoboFormImporter.new.run