module EasyAgileBoard
  module EasyIssueQueryPatch

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

      base.class_eval do

        alias_method_chain :initialize_available_filters, :easy_agile_board
        alias_method_chain :initialize_available_columns, :easy_agile_board

        def sql_for_easy_sprint_id_field(field, operator, value)
          sql = '('
          sql << sql_for_field(field, operator, value, IssueEasySprintRelation.table_name, 'easy_sprint_id')
          sql << ')'
          sql
        end

      end
    end

    module InstanceMethods
      def initialize_available_filters_with_easy_agile_board
        initialize_available_filters_without_easy_agile_board
        group = l(:'easy_query.name.easy_agile_board_query')
        add_available_filter 'easy_sprint_id', {:type => :list_optional, :order => 1, :values => Proc.new{EasyAgileBoard.easy_sprints_for_autocomplete(self.project)}, :group => group, :includes => [:issue_easy_sprint_relation]}
        add_available_filter 'easy_story_points', {:type => :integer, :order => 2, :group => group}
      end

      def initialize_available_columns_with_easy_agile_board
        initialize_available_columns_without_easy_agile_board

        group = l('easy_query.name.easy_agile_board_query')
        @available_columns << EasyQueryColumn.new(:'issue_easy_sprint_relation.easy_sprint', :groupable => true, :sortable => "#{EasySprint.table_name}.name", :caption => :label_agile_sprint, :includes => [:issue_easy_sprint_relation => :easy_sprint], :group => group)
        @available_columns << EasyQueryColumn.new(:easy_story_points, :groupable => true, :sumable => :both, :sortable => "#{Issue.table_name}.easy_story_points", :caption => :label_agile_story_points, :group => group)
      end
    end

  end

end
EasyExtensions::PatchManager.register_model_patch 'EasyIssueQuery', 'EasyAgileBoard::EasyIssueQueryPatch'

