module EasyPatch
  module UserFormatPatch

    def self.included(base)
      base.send(:include, InstanceMethods)
      base.extend(ClassMethods)

      base.class_eval do
        alias_method_chain :possible_values_records, :easy_extensions
      end
    end


    module InstanceMethods

      def possible_values_records_with_easy_extensions(custom_field, object=nil)
        if object.nil?
          User.active.visible.sorted
        elsif object.is_a?(Array)
          projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
          projects.map {|project| possible_values_records(custom_field, project)}.reduce(:&) || []
        elsif object.respond_to?(:project) && object.project
          scope = object.project.users
          if custom_field.user_role.is_a?(Array)
            role_ids = custom_field.user_role.map(&:to_s).reject(&:blank?).map(&:to_i)
            if role_ids.any?
              scope = scope.where("#{Member.table_name}.id IN (SELECT DISTINCT member_id FROM #{MemberRole.table_name} WHERE role_id IN (?))", role_ids)
            end
          end
          scope.active.visible.sorted
        else
          []
        end
      end

    end

    module ClassMethods
    end

  end
end
