require "activerecord/simple_count/version"
require 'active_record/relation/calculations'

module Activerecord
  module SimpleCount
    #extend ActiveRecord::Calculations
    def simple_count(column_name = nil, options = {})
      if column_name.is_a?(Symbol) && attribute_alias?(column_name)
        column_name = attribute_alias(column_name)
      end

      column_name = primary_key if column_name == :all
      relation = unscope(:order)

      column_alias = column_name
      bind_values = nil

      column = aggregate_column(column_name)

      select_value = column.count(false)

      column_alias = select_value.alias
      relation.select_values = [select_value]

      query_builder = relation.arel
      bind_values = query_builder.bind_values + relation.bind_values

      result = @klass.connection.select_all(query_builder, nil, bind_values)
      row    = result.first
      value  = row && row.values.first
      value.to_i
    end

    def aggregate_column(column_name)
      if @klass.column_names.include?(column_name.to_s)
        Arel::Attribute.new(@klass.unscoped.table, column_name)
      else
        Arel.sql(column_name == :all ? "*" : column_name.to_s)
      end
    end

  end
end

module ActiveRecord
  module Calculations
    prepend Activerecord::SimpleCount
  end
end


