class Photo < ActiveRecord::Base
  mount_uploader :image, ImageUploader
  
	before_validation do
		self.tags_cache = self.tags_cache.to_s.gsub(/ +/, ' ').gsub(/, /,',').gsub(/ ,/,',').gsub(/,+/, ',')
		
	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
