class PProductSubCat < ApplicationRecord
  has_many :p_product_p_product_sub_cats, :dependent => :destroy
  
  attr_accessor :skip_before_update, :skip_permalink
  
  has_many :p_products, :through => :p_product_p_product_sub_cats
  
  acts_as_tree
  
  validates :code, :presence => true, uniqueness: { scope: :parent_id}
  validates :name, :presence => true
  
  def member_label
    "#{self.code} #{self.name}"
  end
  
  
	before_create do
		if !position
			top = PProductSubCat.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?
				
				PProductSubCat.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
				
				PProductSubCat.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
		PProductSubCat.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
