class InformationRankingHistory < ActiveRecord::Base
  
  attr_accessible :excuse, :information_ranking_id, :information_standard_id, :institution_id, :observations, :score, :observations_date

  ##
  # Non dabase attributes

  attr_accessible :information_standard_criterium_ids

  ##  
  # Associations

  belongs_to :user
  belongs_to :institution
  belongs_to :information_ranking
  belongs_to :information_standard
  has_and_belongs_to_many :information_standard_criteria, join_table: :information_ranking_histories_criteria
  has_many :information_ranking_history_views, dependent: :destroy
  has_and_belongs_to_many :excuse_note_criteria
  has_many :information_ranking_history_comments, dependent: :destroy
  accepts_nested_attributes_for :information_ranking_history_comments, reject_if: proc { |comment| comment['comment'].blank? }

  before_save :set_calculated_score

  def set_calculated_score    
    if excuse?
      calculated_score = excuse_note_criteria.map(&:percent).sum
    else
      calculated_score = information_standard_criteria.map(&:percent).sum
    end
    write_attribute(:score, calculated_score)
  end

  def new_coments_for?(user)
    if user == self.user && information_ranking_history_comments.empty?
      return false
    end
    
    last_user_view = information_ranking_history_views.where(user_id: user.id).last

    if !observations_date.nil? && last_user_view.nil?
      return true
    end

    if !observations_date.nil? && observations_date > last_user_view.updated_at
      return true
    end

    if information_ranking_history_comments.any?
      if information_ranking_history_comments.last.created_at > last_user_view.updated_at
        return true
      end
    end
    false
  end
end
