#!/usr/bin/ruby

require 'rubygems'
require 'xmlsimple'

def html_header(site='Stack Exchange')
  return <<END_OF_HTML
<html>
  <head>
    <title>#{site}</title>
    <style type="text/css">
div.post {
  border: 1px solid black;
  margin: 10px;
  padding: 10px;
}
div.question.container {
  border-color: #009;
}
div.question.answer {
  border-color: #090;
}
div.score {
  float: left;
  padding: 5px;
  border: 1px solid #bbb;
}
    </style>
  </head>
  <body>
    <div id="posts">
END_OF_HTML
end

def html_footer()
  return <<END_OF_HTML
    </div>
  </body>
</html>
END_OF_HTML
end

def main(dir)
  xml = XmlSimple.xml_in("#{dir}/posts.xml", { 'KeyAttr' => 'name' })
  
  questions = {}
  
  puts html_header()
  #puts xml['row'].inspect
  xml['row'].each do |post|
    if post['PostTypeId'] == '1'
      questions[post['Id']] = {
        :title => post['Title'],
        :body => post['Body'],
        :score => post['Score'],
        :answers => []
      }
    elsif post['PostTypeId'] == '2'
      questions[post['ParentId']][:answers] << {
        :body => post['Body'],
        :score => post['Score']
      }
    end
  end
  questions.each do |id,question|
    puts "<div class=\"question post container\"><h1>#{question[:title]}</h1><div class=\"score\">#{question[:score]}</div><div class=\"question body\">#{question[:body]}</div>\n"
    question[:answers].each do |answer|
      puts "<div class=\"answer post container\"><div class=\"score\">#{answer[:score]}</div><div class=\"answer body\">#{answer[:body]}</div></div>\n"
    end
    puts "</div>\n"
  end
  puts html_footer()
end

main(ARGV[0])
