require 'div'
require 'singleton'
require 'dirp-access'
require 'devel/logger'
require 'hotpage'
require 'mutexm'
require 'parsedate'

class HotlinksDiv < Div::Div
  include Singleton
  include MutexM

  attr_accessor :server
  attr_accessor :proxy	# Not supported now.
  attr_accessor :size

  DefaultDIRPServer = 'dirp://www.jin.gr.jp:7571/'
  AgentName = 'KinofingerCLIENT'
  From = 'nahi@keynauts.com'

  InitialCoverSec = 7 * 24 * 3600	# 1 week
  CoverSec = 2 * 60 * 60 + 10 * 60	# 2 hour + 10 min
  UpdateInterval = 10 * 60		# 10 min.

  def initialize
    @size = 10
    @session = nil
    @div_class = type.to_s
    @div_id = self.id.to_s
    @action = nil

    @server = DefaultDIRPServer
    @proxy = nil
    @log = Devel::Logger.new( '/var/tmp/hotlinks-div.log' )
    @client = Dirp::Client.new( AgentName, From )
    @client.debugDev = STDOUT
    @client.protocolVersion = '0.3.5'

    @hotItemPool = HotPage.new( &self.method( :hotOrder ))

    @t = Thread.new { poll }
  end

  def to_html(context)
    "<table border='0' width='100%' cellpadding='0' cellspacing='3'>\n" <<
    "<tr><th><small>" <<
    "<a href=\"http://www.ruby-lang.org/ja/hotlinks.html\">Hotlinks</a>" <<
    "</small></th></tr>\n" <<
      hotitem.collect { | di |
	name = di['title']
	author = di['author-name']
	url = di['url']
	t = di['last-modified']
	update = format( '%02d-%02dT%02d:%02d', t.mon, t.mday, t.hour, t.min )
	title = "by #{ author }"
	<<__HERE__
<tr><td><small><a href="#{ url }" title='#{ h( title ) }'>#{ h( name ) }</a>, #{ update }</small></td></tr>
__HERE__
      }.join( "" ) <<
    "</table>\n"
  end

private

  def hotitem
    synchronize do
      @hotItemPool.pages[ 0, @size ]
    end
  end

  def poll
    milestone = Time.at( Time.now.gmtime - InitialCoverSec )
    while true
      begin
  	t = milestone
   	milestone = Time.at( Time.now.gmtime - CoverSec )
    	condition = {
	  'if-detected-modified-since' =>
	    t.strftime( "%a, %d %b %Y %H:%M:%S GMT" ),
	  'keyword' => 'Ruby'
	}
	@log.debug { condition.inspect }
	oldItems = @hotItemPool.__pages
	conn = @client.get( @server, condition ) { | di |
	  parsed = ParseDate.parsedate( di['last-modified'] )
	  di['last-modified'] = Time.gm( *parsed[ 0..5 ] ).localtime
	  synchronize do
	    old = oldItems.find { |i| i['url'].downcase == di['url'].downcase }
	    if old
	      @hotItemPool.delete( old )
	    end
	    @hotItemPool << di
	  end
	}
	@log.info "Got #{ conn.diBlock.size } items."
	sleep UpdateInterval
      rescue Exception
	@log.fatal $!
      end
    end
  end

  def hotOrder( a, b )
    b['last-modified'] <=> a['last-modified']
  end
end

if __FILE__ == $0
  a = HotlinksDiv.instance
  while true
    p a.to_html(nil)
    sleep 10
  end
end
