class Impression
  include Mongoid::Document
  include Mongoid::Timestamps

  field :impressionable_type
  field :impressionable_id
  field :user_id
  field :controller_name
  field :action_name
  field :view_name
  field :request_hash
  field :ip_address
  field :session_hash
  field :message
  field :referrer

  belongs_to :impressionable, :polymorphic => true

  after_save :update_impressions_counter_cache

  def self.impressionist_count(options={})
    options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now)
    imps = options[:start_date].blank? ? impressions : impressions.where(:created_at.gte => options[:start_date], :created_at.lte => options[:end_date])
    options[:filter] == :all ? imps.count : imps.distinct(options[:filter]).count
  end

  private

  def update_impressions_counter_cache
    if self.referrer
      impressionable_class = self.impressionable_type.constantize

      if impressionable_class.impressionist_counter_cache_options
        resouce = impressionable_class.find(self.impressionable_id)
        resouce.try(:update_impressionist_counter_cache)
      end
    end
  end
end
