require 'drb/drb'
require 'div'
require 'config'
require 'reminder-div'
require 'todo-div'
require 'paper-div'
require 'rwiki-div'

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

  def initialize(session)
    super(session)
    @status = nil
  end

  def show
    @status = :show
  end

  def do_show(conext, params)
    show
  end

  def do_guest(context, params)
    login(@session, 'guest', nil)
  end
  
  def do_login(context, params)
    username, = params['username']
    password, = params['password']
    login(@session, username, password)
  end

  def login(session, username, password)
    begin
      session.login(username, password)
      @status = :succ
    rescue
      @status = :fail
    end
  end
end

class Banner < Div::Div
  set_erb('banner.erb')
end

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

  def initialize(session)
    super
    @banner = Banner.new(session)
    @login = LoginDiv.new(session)
    @login.show
    @reminder = ReminderDiv.new(session, $reminder)
    @todo = TodoDiv.new(session, $todo)
    @paper = PaperDiv.new(session, $paper)
    @rwiki = RWikiDiv.instance
  end
end

class MySession < Div::Session
  def initialize(req, hint=nil)
    super(req, hint)

    @username = 'guest'
    @base = Base.new(self)
    @status = :init
  end
  attr_reader :username, :status
  attr_accessor :key

  def login(name, password)
    $login.login(name, password)
    @username = name
    @hint = @username
  end

  def reply(req)
    req.session = @key
    req.hint = @hint
    req.body = @base.to_html(req)
    @status = nil
  end
end

if __FILE__ == $0
  if true
    require 'login'
    $login = Login.instance
    require 'reminder'
    $reminder = Reminder.instance
    require 'todo'
    $todo = Todo.instance
    require 'paper'
    $paper = PaperModel.instance
  else
    $login = DRbObject.new(nil, LOGIN_URI)
    $reminder = DRbObject.new(nil, REMENDER_URI)
  end

  front = Div::App.new(MySession)

  DRb.start_service(APP_URI, front)
  puts DRb.uri

  while s = gets
    Div.reload_erb
  end
end
