require 'div/div'
require 'tempura/div'
require 'div/tofusession'

class SumTotal
  def initialize
    @history = []
    @amount = 0
  end
  attr_reader :history, :amount

  def add(value)
    f = value.to_f
    @history.push(f)
    @amount += f
  end
  
  def undo
    tail = @history.pop
    return unless tail
    @amount -= tail
  end
end

module SumDivMixin
  def initialize(session)
    super(session)
    @model = SumTotal.new
  end

  def do_add(context, params)
    value, = params['value']
    @model.add(value)
  end

  def do_reset(context, params)
    @model = SumTotal.new
  end

  def do_undo(context, params)
    @model.undo
  end
end

module BaseDivMixin
  def initialize(session)
    super(session)
    @sum = SumDiv.new(session)
  end
end

case $SUMDIV

when /^e/i then                 # erb
  class SumDiv < Div::Div
    set_erb 'sum.erb'
    include SumDivMixin
  end

when /^t/i                      # tempura
  class SumDiv < Tempura::Div
    set_template 'sum.html'
    include SumDivMixin
  end

end

case $BASEDIV

when /^e/i then                 # erb
  class BaseDiv < Div::Div
    set_erb 'base.erb'
    include BaseDivMixin
  end

when /^t/i                      # tempura
  class BaseDiv < Tempura::Div
    set_template 'base.html'
    include BaseDivMixin
  end

end

class YourTofuSession < Div::TofuSession
  def initialize(bartender, hint=nil)
    super(bartender, hint)
    @base = BaseDiv.new(self)
  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
