require 'div/div'
require 'div/tofusession'
require 'login'
require 'saifu'

class BaseDiv < Div::Div
  set_erb('base.erb')

  def initialize(session)
    super(session)
    @login = MyLoginDiv.new(session, session.login, session.hint)
    @saifu = SaifuDiv.new(session)
  end
end

class YourTofuSession < Div::TofuSession
  def initialize(bartender, hint=nil)
    super(bartender, hint)
    @login = MyLogin.new(SaifuLoginDB.instance)
    @base = BaseDiv.new(self)
  end
  attr_reader :login

  def hint
    if @login.login? && !@login.guest?
      @login.user[:id]
    else
      super
    end
  end

  def do_GET(context)
    update_div(context)
    context.res_header('content-type', 'text/html; charset=euc-jp')
    context.res_body(@base.to_html(context))
  end
end

pool = DBIPool.new(5, 'DBI:Pg:saifu', 'saifu', 'saifu')
SaifuDB.pool = pool
SaifuLoginDB.pool = pool

if __FILE__ == $0
  require 'drb/drb'
  require 'tofu/proxy'

  use_ring = (ARGV.shift == '-r')
  
  tofu = Tofu::Bartender.new(YourTofuSession)
  if use_ring
    require 'rinda/ring'
    require 'tofu/ring'

    DRb.start_service
    
    finder = Tofu::RingTofuletFinder.new
    finder.mount('/saifu', tofu)
    
    DRb.thread.join
  else
    DRb.start_service('druby://localhost:7643', tofu)
    DRb.thread.join
  end
end
