#!/usr/bin/ruby -Ke

require 'rice/irc'
require 'rice/observer'
require 'nkf'

NICK = 'irb'
USER = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME'] || NICK
REAL = 'rice/irb user'

CHANNEL = '#ricetest'

Thread.abort_on_exception = true

o = RICE::SimpleClient.new(NICK, USER, REAL, nil, CHANNEL)
c = RICE::Connection.new('localhost', 9999)
c.add_observer(o)

def o.response_for_privmsg(subject, message)
  @rank ||= {}
  nick = message.prefix.scan(/^[^!]+/o)[0]
  chan = message.params[0]
  text = NKF::nkf('-e', message.params[1..-1].join(' '))
  size = text.size

  now = Time.now
  @start_time ||= now
  @rank_lm    ||= now
  @last_msg   ||= now

  if /^#{NICK} トップ(\d+)?$/o =~ text
    if now - @rank_lm < 10
      return
    end
    @rank_lm = now

    n = $1.to_i if $1
    if !n || n < 1
      n = 3
    elsif n > 10
      n = 10
    end

    t, = (now - @start_time).to_i.to_f/(60*60)
    t = 1.0 if t < 1.0
    r = @rank.keys.sort{|a,b| 
      @rank[b][0]<=>@rank[a][0]}[0...n].reverse
    r.each_with_index do |x,i|
      break unless x
      subject.push notice chan, 
	NKF::nkf('-j', sprintf('第%d位: %s (%d行/H, %dB/H)', 
			       r.size - i, x, @rank[x][0]/t, @rank[x][1]/t))
    end

  else
    if now.hour == 5 && @last_msg.hour != 5
      @yestaday_rank = @rank
      @rank = {}
      @start_time = now
    end
    @rank[nick] ||= [0, 0]
    @rank[nick][0] += 1
    @rank[nick][1] += size
  end

  @last_msg = now
end

def o.response_for_nick(subject, message)
  oldnick = message.prefix.scan(/^[^!]+/o)[0]
  newnick = message.params[0]

  if @rank.include?(oldnick)
    @rank[newnick] = @rank.delete(oldnick)
  end
end

def o.response_for_invite(subject, message)
  nick = message.params[0]
  chan = message.params[1]

  if nick == NICK
    subject.push join chan
  end
end

begin
  c.start
rescue RICE::Connection::Closed
  sleep 30
  retry
end



syntax highlighted by Code2HTML, v. 0.9.1