class Admin::UsersController < ApplicationController
  
  layout "admin"
  before_filter :authenticate_user!
  
  def index
    @users = User.all.entries
  end
  
  def show
    @user = User.find(params[:id])
    get_info_role_models
  end
  
  def new
    @user = User.new
    get_info_role_models
  end
  
  def create
    @user = User.new(params[:user])
    if @user.save
      @user.user_infos.each do |user_info|
        user_info.save
        user_info.attribute_values.each(&:save)
      end
      @user.user_roles.each do |user_role|
        user_role.save
        user_role.attribute_values.each(&:save)
      end
      flash[:notice] = t('admin.create_success_user')
      redirect_to :action => :index
    else
      render :action => :new      
    end
  end
  
  def edit
    @user = User.find(params[:id])
    get_info_role_models
  end
  
  def update
    @user = User.find(params[:id])
    
    # Update changes to the avatar
    @user.remove_avatar! if params[:file]
    @user.avatar = params[:file] if params[:file]
    
    if @user.id.to_s.eql?(session['warden.user.user.key'][1].to_s) && @user.admin != params[:user][:admin].to_i.to_b
      flash.now[:error] = t('admin.cant_revoke_self_admin')
    end
    if !flash[:error] && @user.update_attributes(params[:user])
      flash[:notice] = t('admin.update_success_user')
      redirect_to :action => :index
    else
      get_info_role_models
      render :action => :edit
    end
  end
  
  def destroy
    if params[:id].eql?(session['warden.user.user.key'][1].to_s)
      flash[:error] = t('admin.cant_delete_self')
    else
      @user = User.find(params[:id]) 
      @user.destroy
      @user.user_attributes.each do |ua|
        ua.attribute_values.each(&:destroy)
        ua.destroy
      end
    end
    
    redirect_to :action => :index
  end
  
  protected
  
  def get_info_role_models
    @user_info_models = UserInfoModel.excludes('disabled' => true)
    @user_role_models = UserRoleModel.excludes('disabled' => true)
  end
  
end
