class InformationRanking < ActiveRecord::Base

  attr_accessible :closed, :closed_at, :name, :published, :information_standard_category_id

  # Non database attributes
  attr_accessible :information_ranking_histories_attributes

  # Associations
  belongs_to :information_standard_category
  has_many :information_ranking_histories, dependent: :destroy

  # Validations
  validates :name, :information_standard_category_id, presence: true

  # Nested attributes
  accepts_nested_attributes_for :information_ranking_histories, allow_destroy: true

  # Destroy information ranking histories if their institutions are belongs to
  # a different information standard category than this (self) information ranking
  #
  after_save :destroy_bad_information_ranking_histories_associations
  #
  def destroy_bad_information_ranking_histories_associations
    information_ranking_histories.each do |information_ranking_history|
      if information_ranking_history.institution.information_standard_category_id != information_standard_category_id
        information_ranking_history.destroy
      end
    end
  end

  def score_by_institution(institution)
    score = 0.0
    information_ranking_histories.where(institution_id: institution.id).each do |history|
      info = InformationStandardInfo.where(information_standard_id: history.information_standard_id, information_standard_category_id: information_standard_category.id).first
      score += (history.score / 100 / 10 * (info.nil? ? 0 : info.percent))
    end
    score
  end

  def has_scores_for_institution?(institution)
    information_ranking_histories.where(institution_id: institution.id).pluck(:score).sum > 0
  end

  def has_scores_for_standard?(standard)
    information_ranking_histories.where(information_standard_id: standard.id).pluck(:score).sum > 0
  end
end
