class Article < ActiveRecord::Base
  
  has_many :comments, :as => :commentable
  
  belongs_to :image_file
	validates :title, :presence => true
	validates :slug, :presence => true, :uniqueness => true
	has_one :block, :as => :blockable
	
	belongs_to :category
	has_many :enabled_comments,-> {where(:enabled => true)}, :source => :comments, :as => :commentable
	after_create :after_creation
	
  
  HUMAN_NAME =  "lien vers un article."
  
	before_validation do
		self.slug = self.slug.to_slug
		self.tags_cache = self.tags_cache.gsub(/ +/, ' ').gsub(/, /,',').gsub(/ ,/,',').gsub(/,+/, ',')
    self.tags_cache = self.tags_cache.to_s.gsub(/ +/, ' ').gsub(/, /,',').gsub(/ ,/,',').gsub(/,+/, ',')
		
	end
	
	

	def after_creation
	    @block = Block.new(:block_name => "Contenu")
		@block.blockable = self
		@block.save
		
		
	end
  
  def alloweds_types
  self.block.allow_types :TitleContent, :TextContent, :ImageContent, :LinkContent, :GalleryContent, :HtmlContent
  
  end
  
	
	scope :recents, -> {where("enabled = ?",true ).order("published_at DESC, created_at DESC")}
	
	scope :between, lambda { |start, stop|
	        after(start).before(stop)
	    }
	
	scope :after, lambda { |date|
	        where("(published_at >= ?)", date )
	    }
	scope :before, lambda { |date|
	        where("(published_at <= ?)", date )
	    }

	
	
	after_initialize do
	    if self.published_at			
			self.published_at = self.published_at.strftime('%d/%m/%Y')
		end
	
	end
  
  

	
	
	before_save do
		#self.tags_cache = nil
		
		tag_list = self.tags_cache.split(',').uniq

		tag_names = []
		tag_objects_list = []

		tag_list.each do |tag_name|
			if tag = Tag.create(:name => tag_name.capitalize) and tag.id
				self.tags << tag
			else
				tag = Tag.find_by_slug(tag_name.to_slug)
				self.tags << tag if !self.tags.include?(tag)
			end
			tag_objects_list << tag
			tag_names << tag.name
		end
    self.tags_cache = tag_names.sort.join(",").to_s
		tags_to_remove = tags - tag_objects_list
		tags_id_to_remove = (tags - tag_objects_list).map {|t| t.id}
		self.tag_taggables.where(:tag_id => tags_id_to_remove).each { |t| t.destroy }
    
    
	end
	
	
	
	has_many :tag_taggables, :as => :taggable
	has_many :tags, :through => :tag_taggables 
  
  def generate_tags_cache
    self.tags_cache = self.tags.map{|a| a.name}.join(",").to_s
  end
  
  def tag_by_tag_ids(tags_id)
    Tag.find(tags_id).each do |tag|
      self.tags << tag if !self.tags.include?(tag)
    end
    self.generate_tags_cache
    self.save
    
  end
  
	before_destroy do
    self.tags_cache = ""
    self.save
  end


end