class Ability
  
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    #   user ||= User.new # guest user (not logged in)
    #   if user.admin?
    #     can :manage, :all
    #   else
    #     can :read, :all
    #   end
    #
    # The first argument to `can` is the action you are giving the user permission to do.
    # If you pass :manage it will apply to every action. Other common actions here are
    # :read, :create, :update and :destroy.
    #
    # The second argument is the resource the user can perform the action on. If you pass
    # :all it will apply to every resource. Otherwise pass a Ruby class of the resource.
    #
    # The third argument is an optional hash of conditions to further filter the objects.
    # For example, here the user can only update published articles.
    #
    #   can :update, Article, :published => true
    #
    # See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities

    user ||= User.new # guest user (not logged in)
    if user.new_record?
    else
      can :manage, Profile
      user.permissions_roles.each do |permissions_role|        
        if permissions_role.permission.subject_class.to_sym == :all
          can permissions_role.permission.action.to_sym, :all
        elsif permissions_role.conditions.nil?
          can permissions_role.permission.action.to_sym, permissions_role.permission.subject_class.constantize
        else
          if [:user, :role].include? permissions_role.permission.subject_class.downcase.to_sym
            can permissions_role.permission.action.to_sym, permissions_role.permission.subject_class.constantize, { :user_id => ( user.role.user_ids rescue user.id ) }
            can permissions_role.permission.action.to_sym, permissions_role.permission.subject_class.constantize, permissions_role.symboled_conditions.symbolize_keys if permissions_role.symboled_conditions.present?
          else
            can permissions_role.permission.action.to_sym, permissions_role.permission.subject_class.constantize, permissions_role.symboled_conditions.symbolize_keys
          end
        end
      end
    end
  end
end
