class Category < ApplicationRecord
	has_many :articles
	
	
  has_many :category_langs, :dependent => :destroy
  accepts_nested_attributes_for :category_langs
  
  has_many :category_animalables, :as => :categoryalable
  has_many :categoryalable, :through => :category_animalables
  
  has_many :category_categoryables
	
  attr_accessor :skip_before_update, :skip_permalink
  acts_as_tree
  
  
  
  
  def name 
    self.lang("fr").name
  end
  
	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
	
	
	
	
	




	before_create do
		if !position
			top = Category.where( :parent_id => self.parent_id).order("position DESC").first
			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
  
  
  def lang(locale)
    self.category_langs.find_by_lang_site_id(LangSite.find_by_slug(locale).id)
  end
  
  
  
  

end
