#!/usr/bin/env ruby
#
# Gets problems from the UVa website, in order of solvability.
#
# Sample page:
# http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3

require 'nokogiri'
require 'open-uri'

begin
  if ARGV.empty?
    puts <<-END
    Usage:
        uva-difficulty-searcher url"

    url:   uva url
    END
    exit 666
  end

  root_page = nil

  root_page = ARGV.last

  page = Nokogiri::HTML(open(root_page))
  table = page.css('body div#col3 table')[0]

  summaries = []

  table.css('tr').each_with_index do |t, i|
    next if i == 0
    a = []
    title = t.css('td')[1].text.delete("\n")
    number = title[0..2].to_i
    text   = title[6..(title.length)]
    a.push number
    a.push text
    a.push t.css('td')[3].text.delete("\n").delete("%").gsub(/\s/, "")
    summaries.push a
  end

  # Sorting based on percentage of solutions
  summaries.sort! do |a, b|
    b[2].to_f <=> a[2].to_f
  end

  puts "UVa problems in order of solving"
  puts "id|name|solving-percentage"
  summaries.each do |s|
    puts "#{s[0].to_s}|#{s[1]}|#{s[2]}%"
  end
end