class AlbumFolder < ActiveRecord::Base
  
  acts_as_tree
  has_many :albums
  validates :name, :presence => true
  attr_accessor :nested_children_ids_var, :no_image_count
  
  
  def explore_ids(af)
   @nested_children_ids_var << af.id
   puts af.id
    self.children.each do |af|
      
      af.explore_ids(af)
      
    end
  end
  
  def nested_children_ids
    
    @nested_children_ids_var = [self.id]
    
    self.children.each do |af|
      
      af.explore_ids(af)
      
    end
    
    @nested_children_ids_var = @nested_children_ids_var.uniq!
    
    
  end
  
  def self_and_descendants_ids
    self.self_and_descendants.map(&:id).uniq 
  end
  
  def self_and_descendants_albums
    Album.where(:album_folder_id => self.self_and_descendants_ids)
  end
  
  def self_and_descendants_albums_ids
    self.self_and_descendants_albums.map(&:id).uniq
  end
  
  
  def image_files
    ImageFile.where(:album_id => self.self_and_descendants_albums_ids)
  end
  
  
  def update_image_count 
    puts "update"
    self.images_count_cache = self.image_files.count
    self.no_image_count =  true
    self.save
    
    
    
  end
  
  def self.update_image_counts
    AlbumFolder.all.each do |album_folder|
      album_folder.update_image_count
    end
    
  end
  
  
  after_save do 
    if !self.no_image_count
      self.no_image_count =  true
      self.update_image_count
    
      self.ancestors.each do |ancest|
        ancest.no_image_count =  true
        ancest.update_image_count
      
      end
    end
      
    
    
  end
  
  
  
end
