require 'div/div'
require 'div/tofusession'
require 'rwiki/rw-tofu'
require 'rw-proxy'

class RWikiEditSession < Div::TofuSession
  def initialize(bartender, hint=nil)
    super(bartender, hint)
    @rwiki = RWikiProxy.instance.rwiki
    @rwiki_service = RWiki::TofuService.new(@rwiki)
    @login_div = LoginDiv.new(self)
  end

  def do_GET(context)
    unless @login_div.login    
      update_div(context) 
      if @login_div.login
	@rwiki_service.redirect_to_top(context)
      else
	context.res_header('cache-control', 'no-cache')
	context.res_header('content-type', 'text/html; charset=euc-jp')
	context.res_body(@login_div.to_html(context))
      end
      return
    end
    @rwiki_service.do_GET(context)
  rescue Errno::ECONNREFUSED
    @rwiki_service.on_rwiki_server_down(context)
  rescue
    context.res_header('status', '400')
    context.res_header('content-type', 'text/plain')
    context.res_body('CGI(?) exec failed.')
  end
end

class RWikiEditSession
  class LoginDiv < Div::Div
    set_erb('rw-login.erb')
    
    @@phrase = 'rrrrwiki'
    def self.phrase=(str)
      @@phrase = str
    end

    def initialize(session)
      @login = nil
      @message = nil
      super(session)
    end
    attr_reader :login, :message
    
    def do_login(context, params)
      name ,= params['name']
      phrase ,= params['phrase']

      if @@phrase == phrase
	@login = name
	@message = ''
      else
	@login = nil
	@message = 'bad-phrase'
      end
    end
  end
end

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

  puts("phrase:")
  phrase = gets.chomp
  RWikiEditSession::LoginDiv.phrase = phrase

  DRb.start_service
  
  tofu = Tofu::Bartender.new(RWikiEditSession)

  ts = Rinda::RingFinger.primary

  tuple = ts.read([:name, :Tofulet, nil, nil])
  webrick = tuple[2]
  webrick.mount('/edit', DRbObject.new(tofu))

  while gets
    Div.reload_erb
  end
end
