class Category < ActiveRecord::Base
	has_many :articles
	
	validates :name, :presence => true, :uniqueness => true
	validates :slug, :presence => true, :uniqueness => true
	
	before_validation do
		self.slug = self.name.to_slug
    self.validate_permalink
		
	end
  attr_accessor :skip_before_update, :skip_permalink
  acts_as_tree
  
  
  
  
  
  
	def generate_permalink
		r = ""
		
		node, ancestors = self, []
		ancestors << node = Category.find(node.parent_id) while node.parent_id?
		      
		
		
		ancestors.reverse.each do |ancestor|
			r += ancestor.slug.to_s
			r+= "/"
		end
		r+= self.slug.to_s
	end
	
	def set_permalink
		
		
		if !skip_permalink
			
			self.permalink = self.generate_permalink
			self.skip_permalink = true
			self.skip_before_update = true
			
			
			
			self.save

		end
		
	end
	
	
	
	def validate_permalink
		self.parent_id = nil if self.parent_id == 0
		errors.add(:parent_id, 'doit être différent de la page actuelle') if parent_id == id and id != nil
		
		if self.id
			errors.add(:parent_id, 'attention la page parente à pour page parente celle-ci = boucle') if self.parent_id and self.id == Category.find(self.parent_id).parent_id
		end

		conditions = ["parent_id "+(self.parent_id ? "=" : "IS")+" ? and slug = ? "+("and id != ?" if self.id).to_s,self.parent_id ,self.slug]
		conditions << self.id if self.id
		if Category.where(conditions).first
			errors.add(:slug, 'est déjà utilisé') 
			
		end
		

	end
	
	




	before_create do
		if !position
			top = Category.where( :parent_id => self.parent_id).order("position DESC")
			if top
				self.position = top.position.to_i + 1
			else
				self.position = 1
			end
		end
		
	end

	before_update do
	
			if self.parent_id_changed?
				
				Category.where(["position > ? and parent_id "+(self.changes['parent_id'][0] ? "=" : "IS")+" ?",self.position,self.changes['parent_id'][0]]).each do |portlet|
					portlet.position = portlet.position - 1
					portlet.save!
				end
				
				self.position = 1
				
				Category.where(["parent_id "+(self.parent_id ? "=" : "IS")+" ?",self.parent_id]).each do |portlet|
					portlet.position = portlet.position + 1

					portlet.save!
				end
				
				
				
				
			
		end
	end

	before_destroy do
		Category.where(["position > ? and parent_id "+(self.parent_id ? "=" : "IS")+" ?",self.position,self.parent_id]).each do |portlet|
			portlet.position = portlet.position - 1
			portlet.skip_before_update = true
			portlet.save!
		end

	end
  
  
  
  
  

end
