
# using 
#   ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin9]
#   firewatir (1.6.2)
#   firefox 3.5.2

require "rubygems"
require "firewatir"
require 'benchmark'
require 'open-uri'
require 'pp'

PAGE_MAX = 2 # 999
QUERY = 'micro bikini'
DOWNLOAD_DIR = 'download'

@saved_num = 0

def save_image url
  begin
    url.gsub!('%252', '%2')  # %2520 -> $20, #252B -> #2B

    save_path = "#{DOWNLOAD_DIR}/'#{URI.decode(File.basename(url))}"
    open(save_path, 'wb') do |file|
      open(url) do |data|
        file.write(data.read)
      end
    end
    @saved_num += 1
    puts "#{@saved_num}   Saved: #{save_path}"
  rescue => ex
    pp "-- Error for #{url}"
    pp ex
  end
end

def get_next_link(browser)
  next_link = nil
  browser.links.each do |link|
    next_link = link if link.div(:id, "nn").exists?
  end
  next_link
end

browser = FireWatir::Firefox.new
sleep 3

puts Benchmark.measure {
  browser.goto('http://images.google.com/imghp?hl=en')  # ボタンを名前で探すので英語モードにする

  browser.text_field(:name, "q").set QUERY   # 検索語をセット
  browser.button(:value, "Search Images").click # 検索実行

  # 保存先 Filder の作成
  Dir::mkdir(DOWNLOAD_DIR) unless File.exist?(DOWNLOAD_DIR)

  1.upto(PAGE_MAX) do |page|

    if page != 1
      # [次] があれば次ページへ行く。なければ終了する。
      next_link = get_next_link(browser)
      break if next_link == nil
      next_link.click
    end

    pp "-- page #{page}"
    browser.links.each do |link|
      /imgurl=(.*)&imgrefurl/ =~ link.href
      image_url = $1      
      save_image image_url  if image_url != nil and image_url != ''
    end
  end
}

# browser.close dows not work.
# See http://jira.openqa.org/browse/WTR-272
system("echo 'tell application \"Firefox\" to quit' | osascript -")
