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

class SimpleLogin < Div::Login
  def initialize
    super
    @keys = {'seki' => 'seki00'}
  end

  def get_user(user, pass)
    if @keys[user] && @keys[user] == pass
      user
    else
      nil
    end
  end
end

class SimpleLoginDiv < Div::LoginDiv
  set_erb('login.erb')
end

class FailedLoginDiv < Div::LoginDiv
  set_erb('flogin.erb')
  def initialize(session, model, hint)
    super(session, model, hint)
    reset_count
    p @hint
  end
  attr_reader :failed_count

  def do_login(context, params)
    super(context, params)
    if @login.login?
      @failed_count = 0
      @failed = false
    else
      @failed_count += 1
      @failed = true
    end
    @login.guest_login if @failed_count > 3
  end
  
  def do_logout(context, params)
    super(context, params)
    reset_count
  end

  private
  def reset_count
    @failed_count = 0
    @failed = false
  end
end

class YLoginDiv < Div::LoginDiv
  set_erb('ylogin.erb')
  def initialize(session, model, hint)
    super(session, model, hint)
    @login.guest_login unless @login.login?
  end
  
  def do_begin(context, params)
    @login.logout
  end
end

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

  def initialize(session)
    super(session)
    @flogin = FailedLoginDiv.new(session, session.login, session.hint)
    @login = SimpleLoginDiv.new(session, session.login, session.hint)
    @ylogin = YLoginDiv.new(session, session.login, session.hint)
  end
end

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

  def hint
    if @login.login? && !@login.guest?
      @login.user.to_s
    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
