class NeedCategory < ActiveRecord::Base
  attr_accessor :level
  
  has_many :domains, :through => :domain_need_categories
  has_many :domain_need_categories, :dependent => :destroy
  
  
  scope :top, -> {
    where(parent_id: nil)
  }

  belongs_to :parent, class_name: "NeedCategory", foreign_key: :parent_id
  has_many :categories, class_name: "NeedCategory",  foreign_key: :parent_id, dependent: :destroy
  validates :name, :presence => true, length: {within: 1..64}

  scope :domain_in, -> (domain_ids) {
    joins(:domains).where('domains.id IN(?)', domain_ids)
  }

  def level=(level)
    @level = level
  end

  def ancestors
    node, ancestors = self, []
		ancestors << node = NeedCategory.find(node.parent_id) while node.parent_id?
    ancestors
  end

  def self.create_tree(top_level_categories=false)
    collection = []
    level = 0
    top_level_categories = NeedCategory if !top_level_categories
    top_level_categories = top_level_categories.order(name: :asc).top
    self.populate_collection(collection, top_level_categories, level)
    collection
  end

  def self.populate_collection(collection, categories, level)
    categories.each do |c|
      c.level = level
      childs = c.categories.order(name: :asc)
      collection << c
      self.populate_collection(collection, childs, level + 1)
    end
  end

  def self.populate_ids(ids, categories)
    categories.each do |c|
      ids << c.id
      childs = c.categories
      self.populate_ids(ids,childs)
    end
  end

  def child_ids
    ids = []
    ids << self.id
    NeedCategory.populate_ids(ids, self.categories)
    ids
  end

end
