#START:add_user
class LoginController < ApplicationController
#END:add_user

#START:add_user
  layout "admin"  # <label id="code.depot18.layout"/>
#END:add_user

  before_filter :authorize, :except => :login

#START:index
  def index
    @total_orders = Order.count
    @pending_orders = Order.count_pending
  end
#END:index

  # just display the form and wait for user to
  # enter a name and password
  #START:login
  def login
    if request.get?
      session[:user_id] = nil
      @user = User.new
    else
      @user = User.new(params[:user])
      logged_in_user = @user.try_to_login

      if logged_in_user
        session[:user_id] = logged_in_user.id
        redirect_to(:action => "index")
      else
        flash[:notice] = "Nom d'utilisateur ou mot de passe invalide"
      end
    end
  end
  #END:login

  #START:add_user
  def add_user
    if request.get?
      @user = User.new
    else
      @user = User.new(params[:user])
      if @user.save
        redirect_to_index("User #{@user.name} created")
      end
    end
  end

  # . . .
  #END:add_user

  def delete_user
    id = params[:id]
    if id && user = User.find(id)
      user.destroy
      flash[:notice] = "User #{user.name} deleted"
    end
    redirect_to(:action => :list_users)
  end

  def list_users
    @all_users = User.find(:all)
  end

  def logout
    session[:user_id] = nil
    flash[:notice] = "Logged out"
    redirect_to(:action => "login")
  end

end
