class StoreController < ApplicationController

  def index
    @products = Product.salable_items
  end

  def add_to_cart
    product = Product.find(params[:id])
    @cart = find_cart
    @cart.add_product(product)
    redirect_to(:action => 'display_cart')
  rescue
    logger.error("Tentative d'accès à un produit invalide #{params[:id]}")
    redirect_to_index('Produit invalide')
  end
  
#START:display_cart
  def display_cart
    @cart = find_cart
    @items = @cart.items
    if @items.empty?
      redirect_to_index("Votre panier est actuellement vide")
    end

    if params[:context] == :checkout
      render(:layout => false)
    end
  end
#END:display_cart

  def empty_cart
    @cart = find_cart
    @cart.empty!
    redirect_to_index('Votre panier est maintenant vide')
  end

  def checkout
    @cart = find_cart
    @items = @cart.items
    if @items.empty?
      redirect_to_index("il n'y a rien dans votre panier")
    else
      @order = Order.new
    end
  end

  # called from checkout view
  def save_order
    @cart = find_cart
    @order = Order.new(params[:order])    #<label id="code.12.new.order"/>
    @order.line_items << @cart.items       #<label id="code.12.add.items"/>
    if @order.save                        #<label id="code.12.save"/>
      @cart.empty!
      redirect_to_index('Merci pour cette commande.')
    else
      render(:action => 'checkout')       #<label id="code.12.redisplay"/>
    end
  end

  private

  # Return a cart object. If we already have one cached
  # in the session, use it, otherwise create a new one 
  # and add it to the session
  def find_cart
    session[:cart] ||= Cart.new
  end

end
