require 'tempura/template'
require 'model'

class Controller

  attr_reader :lang

  def initialize(cginame = "")
    @lang = nil
    @model = Model.new
    @view = Tempura::Template.new
    @view.set "view.html"
    @view.set "view.ja.html", "ja", Tempura::CharConvEUC
    @view.default_action = cginame
  end

  def handle_event(event, params)
    handler = "do_#{event}"
    if respond_to?( handler, true ) then
      send( handler, params )
    end
  end

  def content_type
    result = "text/html"
    result << "; charset=euc-jp" if @lang == "ja"
    return result
  end

  def content_body
    return @view.expand( self, @lang )
  end

  private

  def do_lang(params)
    @lang = params['lang'].first
  end

  def do_add(params)
    name = params['name'].first
    price = params['price'].first.to_i
    @model.add_item(name, price)
  end

  def do_del(params)
    name = params['name'].first
    @model.del_item(name)
  end

  def do_reset(params)
    @model.reset
  end

end
