#!/usr/bin/ruby

require 'dbi'
require 'rss/maker'
require 'yaml'
require 'nicovideo'

print "Content-Type: application/xml\n\n"

yml = YAML.load_file('../genkidama_stats/config.yml')

#nv = Nicovideo.new(yml['nicovideo_mail'], yml['nicovideo_password'])
#nv.login

version = "2.0" # ["0.9", "1.0", "2.0"]

dbh = DBI.connect("DBI:Mysql:#{yml['db_name']}:#{yml['db_host']}",
                  yml['db_user'], yml['db_pass'])
sth = dbh.execute("SELECT REPLACE(video_id, 'low', ''), count(*) FROM nico_video_access_log GROUP BY 1 ORDER BY 2 DESC LIMIT 30")

content = RSS::Maker.make(version) do |m|
m.channel.title = "Genkidama Web Dashboard 0.3"
m.channel.link = "http://genkidama.dokukino.com/"
m.channel.description = "再生数ランキング"
m.items.do_sort = false # sort items by date

sth.fetch do |row|
    i = m.items.new_item
#    begin
#      nv.watch(row[0]) do |v|
#        i.title = v.title
#        sleep 1
#      end
#    rescue Nicovideo::Forbidden => e
#      i.title = e.to_s
#    end
    i.title = "再生回数：#{row[1]}回"
    i.link = "http://www.nicovideo.jp/watch/" + row[0]
    i.date = Time.now
  end
end

print content.to_s
