# hb_today.rb $Revision: 1.1 $
# (C) 2010 pyon
# You can redistribute it and/or modify it under GPL2.

require 'fileutils'
require 'open-uri'
require 'pstore'
require 'rexml/document'
require 'time'
require 'timeout'
require 'uri'

def hb_today_cache_dir(date)
	File::join(@cache_path, 'hb_today', date.strftime('%Y'))
end

def hb_today_cache_file(date)
	File::join(hb_today_cache_dir(date), date.strftime('%Y%m%d.db'))
end

def hb_today_read_cache(date)

	return if !FileTest.exist?(hb_today_cache_file(date))

	begin
		bookmarks = []
		db = PStore.new(hb_today_cache_file(date))
		db.transaction(:read_only) do
			bookmarks = db.fetch(date.strftime('%Y%m%d'), [])
			db.abort
		end
		return bookmarks
	rescue PStore::Error
	end
end

def hb_today_write_cache(date, bookmarks)

	FileUtils.mkdir_p(hb_today_cache_dir(date))

	begin
		db = PStore.new(hb_today_cache_file(date))
		db.transaction do
			db[date.strftime('%Y%m%d')] = bookmarks
			db.commit
		end
	rescue PStore::Error
	end
end

def hb_today_get_xml(date)
	uri = URI::HTTP.build(
		:host  => 'b.hatena.ne.jp',
		:path  => "/#{@conf['hb.user']}/rss",
		:query => "date=#{date.strftime('%Y%m%d')}"
	)
	begin
		timeout(5){uri.read}
	rescue Timeout::Error
	rescue OpenURI::HTTPError
	end
end

def hb_today_html(date, bookmarks)

	datestr = date.strftime('%Y%m%d')

	r =  %Q[<div class="section">\n]
	r << %Q[<h3>]
	r << %Q[<a href="http://b.hatena.ne.jp/#{@conf['hb.user']}/#{datestr}">]
	r << %Q[#{@conf.section_anchor}</a> ]
	r << %Q[<a href="http://b.hatena.ne.jp/#{@conf['hb.user']}/#{datestr}">]
	r << %Q[けふのはてブ</a></h3>\n]
	bookmarks.each do |b|
		r << %Q[<p style="padding-left:1em;text-indent:-1em">]
		r << %Q[<a href="#{h b['link']}">#{h b['title']}</a><br />\n]
		r << %Q[#{h b['tags']}#{h b['description']}</p>\n]
	end
	r << %Q[</div>\n]
end

add_body_leave_proc do |date|
	next '' if /^(latest|month|day)$/ !~ @mode

	bookmarks = hb_today_read_cache(date)
	if !bookmarks.nil?
		next bookmarks.empty? ? '' : hb_today_html(date, bookmarks)
	end

	xml = hb_today_get_xml(date)
	next '' if !xml

	doc = REXML::Document.new(xml).root
	next '' if !doc

	bookmarks = doc.elements.collect('item'){|e|
		tags = e.elements['dc:subject'].nil? ?  '' :
			e.elements.collect('dc:subject'){|s| "[#{s.text}]"}.join('')
		{
			'title'       => e.elements['title'].text,
			'link'        => e.elements['link'].text,
			'description' => e.elements['description'].text,
			'tags'        => tags
		}
	}

	hb_today_write_cache(date, bookmarks)

	next bookmarks.empty? ? '' : hb_today_html(date, bookmarks)
end

