#START:authorize
class AdminController < ApplicationController

  before_filter :authorize

  # ...
#END:authorize

  def index
    list
    render_action 'list'
  end

  def list
    @product_pages, @products = paginate :product, :per_page => 10
  end

  def show
    @product = Product.find(@params[:id])
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(@params[:product])
    if @product.save
      flash['notice'] = 'Produit créé avec succès.'
      redirect_to :action => 'list'
    else
      render_action 'new'
    end
  end

  def edit
    @product = Product.find(@params[:id])
  end

  def update
    @product = Product.find(@params[:id])
    if @product.update_attributes(@params[:product])
      flash['notice'] = 'Produit modifié avec succès.'
      redirect_to :action => 'show', :id => @product
    else
      render_action 'edit'
    end
  end

  def destroy
    Product.find(@params[:id]).destroy
    redirect_to :action => 'list'
  end

  #START:ship
  def ship
    count = 0
    if things_to_ship = params[:to_be_shipped]
      count = do_shipping(things_to_ship)
      if count > 0
        count_text = pluralize(count, "commande")
        flash.now[:notice] = "#{count_text} marquée(s) comme expédiée(s)"
      end
    end
    @pending_orders = Order.pending_shipping
  end

  private

  def do_shipping(things_to_ship)
    count = 0
    things_to_ship.each do |order_id, do_it|
      if do_it == "yes"
        order = Order.find(order_id)
        order.mark_as_shipped
        order.save
        count += 1
      end
    end
    count
  end

  def pluralize(count, noun)
    case count
    when 0: "Aucun(e) #{noun.pluralize}"
    when 1: "Un(e) #{noun}"
    else    "#{count} #{noun.pluralize}"
    end
  end
  #END:ship
  
end
