class InstitutionOrganizationalStructure < ActiveRecord::Base
  # Accessors
  attr_accessible :name, :description, :institution_id, :attendant, :priority
                  :institution_organizational_structures_attributes

  # Associations
  belongs_to :institution
  has_many :institution_organizational_structures, dependent: :destroy
  belongs_to :institution_organizational_structure

  accepts_nested_attributes_for :institution_organizational_structures, reject_if: :all_blank, allow_destroy: true

  # Validations
  validates :name, presence: true
  validates :institution_id, presence: true, if: :is_root?

  # Scopes
  scope :roots, where(institution_organizational_structure_id: nil)
  scope :order_by_priority, order("priority ASC")

  # Delegates
  delegate :name, to: :institution, allow_nil: true, prefix: true

  # Callbacks
  before_save :ensure_institution_id

  # Methods
  def is_root?
    institution_organizational_structure_id.blank?
  end

  def offspring_updated_at
    institution_organizational_structures.map{ |child| [child.priority] + child.offspring_updated_at }.flatten
  end

  def last_updated_at
    return updated_at if institution_organizational_structures.empty?
    offspring_updated_at.max
  end

  def root
    parent = self
    while parent.institution_organizational_structure
      parent = parent.institution_organizational_structure
    end
    parent
  end

  def ensure_institution_id
    self.institution_id = self.root.institution_id rescue nil if !is_root?
  end

  def all_children(children_array = [])
    children_array << self.id
    institution_organizational_structures.each do |child|
      child.all_children(children_array)
    end
    return children_array
  end

  def latest_update
    InstitutionOrganizationalStructure.select(:updated_at).where(id: all_children).order('updated_at desc').first.try(:updated_at)
  end

end
