# encoding:UTF-8
require "rubygems"
require "mechanize"
require "pp"
require "pry"
require "json"

def list_url(page_no)
	#"http://w...content-available-to-author-only...d.net/tlpd/games/index.php?section=hots#tblt-2452-#{page_no}-1-DESC"
	"http://w...content-available-to-author-only...d.net/tlpd/games/index.php?section=hots&action=Update&tabulator_order_col=1&tabulator_order_desc=1&tabulator_page=#{page_no}"
end

def fetch_page(url)
	if @agent.nil?
		@agent = Mechanize.new
		@agent.user_agent_alias = 'Linux Firefox'		
	end
	@agent.get(url)
end

def select_table(doc)
	doc.search("table#tblt_table")
end

def go_prev_page(doc)
	@agent.click(doc.link_with(:text => "<"))
end	

def get_matches(table)
	rows = table.search("tr").collect do |raw_row|
		raw_row.search("td").map{|e| e.text.strip }
	end
	rows.shift
	rows.map{|r|		
			{
				:date => r[1],
				:league => r[2],
				:map => r[3],
				:winner => r[4],
				:loser => r[5]
			}
		}.reverse
end

begin_page, end_page = ARGV.map{|e| e.to_i}

match_list = []
doc = fetch_page list_url end_page

(begin_page..end_page).reverse_each do |page_no|
	print "collecting page #{page_no}..."	
	
	matches = get_matches( select_table(doc) )
	matches.each{ |match|
		match_list << match
	}
	puts "#{match_list.length}"
	
	
	go_prev_page(doc) if page_no != 1 	
end

File.open("matches.json", "w"){|f|
	f.puts JSON.generate(match_list)	
}