# encoding: UTF-8

module Liquid
  module Drops
    class CurrentUser < Drops::User

      allowed_names :current_user

      desc """
        Exposes rights of current user which are dependent
        on your settings and user's role.
        You can call these methods on the returned object:

        - invite_user?
        - create_application?
        - see_log_requests?
      """

      example %{
       {% if current_user.can.see_log_requests? and application.log_requests? %}
          (<a href="{{ application.log_requests_url }}" class="action edit">App Request Log</a>)
       {% endif %}
      }
      def can
        ::Liquid::Drops::CurrentUser::Can.new(@user)
      end

      class Can < Drops::Base

        def initialize(user)
          @user = user
          @provider = user.account.provider_account
        end

        desc "Returns true if can invite users."
        def invite_users?
          ability.can?(:create, ::Invitation)
        end

        desc """User can create application if he/she:

                 - has permission to do so
                 - there is a published (or default) application plan available for at least one service
             """
        def create_application?
          @provider.services.any? do |service|
            ability.can?(:create_application, service) and
              @user.account.can_create_application?(service)
          end
        end

        desc "Returns true if can see log requests."
        def see_log_requests?
          ability.can?(:see, :log_requests)
        end

        private

        def ability
          @ability ||= ::Ability.new(@user)
        end
      end
    end
  end
end
