class EasyEasyQueryQuery < EasyQuery

  def initialize_available_filters
    group = l("label_filter_group_#{self.class.name.underscore}")

    add_available_filter 'user_id', {:type => :list, :order => 7, label: :field_author, :values => Proc.new do
      all_users_values(:include_me => true)
    end,
                                     :group => group
    }
    add_available_filter 'name', {:type => :string, :order => 12, :group => group, :attr_reader => true}
    add_available_filter 'project_id', {
        :type => :list_optional, :order => 1, :values => Proc.new do
          self.all_projects_values(:include_mine => true)
        end,
        :group => group,
        :joins => [:project]
    }
    add_available_filter('role_id', {
        :type => :list_optional,
        :order => 6,
        :values => Proc.new { Role.sorted.map { |r| [r.name, r.id.to_s] } },
        :group => group,
        label: :label_easy_query_visible_for_roles
    })

  end

  def available_columns
    unless @available_columns_added
      @available_columns = [
          EasyQueryColumn.new(:name, :sortable => "#{EasyQuery.table_name}.name"),
          EasyQueryColumn.new(:user, caption: :field_author, :groupable => true, :sortable => lambda { User.fields_for_order_statement('users') }, includes: [:user]),
          EasyQueryColumn.new(:project, :sortable => "#{Project.table_name}.name", :groupable => "#{Project.table_name}.id", :includes => [:project]),
          EasyQueryColumn.new(:default_for_roles, caption: :label_easy_query_default_for_roles, :sortable => "#{Role.table_name}.name", :includes => [:default_for_roles]),
          EasyQueryColumn.new(:roles, caption: :label_easy_query_visible_for_roles, :sortable => "#{Role.table_name}.name", :includes => [:roles]),
          EasyQueryColumn.new(:is_used_as_default_query, caption: :label_easy_query_is_used_as_default_query)
      ]
      @available_columns_added = true
    end
    @available_columns
  end

  def default_list_columns
    super.presence || ['user', 'name', 'project', 'default_for_roles', 'roles']
  end


  def searchable_columns
    ["#{EasyQuery.table_name}.name"]
  end

  def entity_scope
    @entity_scope ||= EasyQuery
  end

  def entity
    EasyQuery
  end

  def entity_easy_query_path(options = {})
    options = options.dup
    options[:type] = self.type
    edit_easy_query_management_path(options)
  end

  def columns_with_me
    super + ['user_id']
  end

  def sql_for_role_id_field(field, operator, value)
    not_op = case operator
    when '!'
      operator = '='
    when '!*'
      operator = '*'
    end
    "#{not_op ? 'NOT ' : ''}EXISTS(SELECT 1 FROM easy_queries_roles WHERE (#{sql_for_field('role_id', operator, value, 'easy_queries_roles', 'role_id')}) AND easy_queries_roles.easy_query_id = easy_queries.id)"
  end

end
