module EasyProjectCom
  module EasyPatch
    module EasyAutoCompletesControllerPatch

      def self.included(base)
        base.send(:include, InstanceMethods)
        base.class_eval do

          alias_method_chain :visible_search_suggester_entities, :easy_project_com

        end
      end

      module InstanceMethods

        def visible_search_suggester_entities_with_easy_project_com
          search_types = EasySetting.value('easy_search_suggester')['entity_types'].to_a & Redmine::Search.available_search_types
          search_types.unshift 'users'
          limit = EasySetting.value('easy_select_limit').to_i

          @proposer_items = EasyExtensions::ActionProposer.get_items(params[:term], limit)
          entity_count = @proposer_items.size

          @suggest_entities = {}
          @suggest_entities[:projects] = get_visible_projects(params[:term], EasySetting.value('easy_select_limit').to_i)
          search_types.each do |search_type|
            klass = search_type.classify.constantize
            @suggest_entities[search_type.to_sym] = klass.search_results(params[:term], User.current, nil, titles_only: true, limit: (limit - entity_count), open_issues: true).to_a
            entity_count += @suggest_entities[search_type.to_sym].size
            break if entity_count == limit
          end

          @suggest_entities.delete_if{|_k, v| v.blank? }

          respond_to do |format|
            format.api { render template: 'easy_auto_completes/entities_with_url', formats: [:api] }
          end
        end

      end

    end
  end
end
EasyExtensions::PatchManager.register_controller_patch 'EasyAutoCompletesController', 'EasyProjectCom::EasyPatch::EasyAutoCompletesControllerPatch'
