class Tag
  include Mongoid::Document
  include Mongoid::Timestamps
  include Impressionist::Impressionable
  
  is_impressionable :counter_cache => { :column_name => :view_count }
  
  field :name, localize: true
  field :cloud_view_count, type: Integer, default: 0
  field :is_default, type: Boolean, default: false
  field :view_count, type: Integer, default: 0

  belongs_to :tag_lease, polymorphic: true
  has_many :taggings, dependent: :destroy

  validates :name, :at_least_one => true

  before_destroy :destroy_module_tag, if: Proc.new { |tag| tag.tag_lease_type.eql?("ModuleTag") }

  protected
  
  def self.get_impressionist(item_tag = self)
    item_tag.impressions.where(:created_at.gte=> 14.days.ago,:created_at.lte => Time.now).count
  end

  private

  def destroy_module_tag
    ModuleTag.without_callback(:destroy, :before, :destroy_tag) do
      self.tag_lease.destroy
    end
  end

end
