


Buildwise::App.controllers :users do
  
  get "/new" do
    authenticate_admin!
    @user = User.new
    if defined?(SERVER_DIGEST)      
      @user.server_digest = SERVER_DIGEST
    end
    
    render "/users/edit"
  end
  
  
  get "/:id/edit" do
    if defined?(SERVER_DIGEST)      
      @user = User.where(:server_digest => SERVER_DIGEST).where(:id => params[:id] || params[:user_id]).first
    else    
      @user = User.where(:id => params[:id] || params[:user_id]).first
    end
    
    authenticate_admin_or_self!
    render "/users/edit"
  end

  post "/update" do
    if defined?(SERVER_DIGEST)      
      @user = User.where(:server_digest => SERVER_DIGEST).where(:id => params[:id] || params[:user_id]).first
    else    
      @user = User.where(:id => params[:id] || params[:user_id]).first
    end
    authenticate_admin_or_self!    
    
    if params[:password] != params[:password_confirmation]
      @error = "Password does not match"
      flash[:alert] = @error
      redirect "/users/#{@user.id}/edit?error=#{@error}"
      return
    end
    
    new_user_flag = false
    
    if @user.nil?
      @user = User.new      
      if defined?(SERVER_DIGEST)      
        @user.server_digest = SERVER_DIGEST
      end
      @user.username = params[:username]
      @user.password = params[:password]
      @user.email = params[:email]            
      new_user_flag = true
    else
      if !params[:username].blank?
        @user.password = params[:username]
      end
      if !params[:email].blank?
        @user.email = params[:email]
      end
      if !params[:password].blank?
        @user.password = params[:password]
      end
    end
    
     
    if @user.save
      params.keys.each do |key|
        if key =~ /^project_(\d+)/                         
          project = Project.where(:id => $1).first
          if project
            
            selected_roles = params[key]
            selected_roles.each do |role_name, checked|                  

              if checked && checked.to_s == "true"
                @user.add_role(role_name, project)  unless @user.has_role?(!role_name, project)
              else

                @user.remove_role(role_name, project)  unless @user.has_role?(!role_name, project)
              end

            end
            
          end       
        end
      end
      
      if new_user_flag
        flash[:info] = "New user added successfully"
      else
        flash[:info] = "Password updated successfully"
      end
      
      
      redirect "/admin/permissions"        
    else
      render "/users/edit".to_sym    
    end
    
  end

end