#!/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 DISTINCT REPLACE(video_id, 'low', '') FROM nico_video_access_log ORDER BY id DESC LIMIT 30")

content = RSS::Maker.make(version) do |m|
m.channel.title = "Genkidama Web Dashboard 0.3 rss - test version "
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[0]
    i.link = "http://www.nicovideo.jp/watch/" + row[0]
    i.date = Time.now
	i.description = "<strong>test title</strong><br/><img src='http://tn-skr1.smilevideo.jp/smile?i=4515676'/>"
  end
end

print content.to_s
