class Player < ApplicationRecord

  validates_presence_of :name, message: I18n.t('please_type_your_name_to_continue')

  has_many :answers, dependent: :destroy


  def update_answer_cache
    self.update_column(:answer_cache, self.answers.ordered.pluck(:value))
  end


  def stats
    total_players_with_score = Player.where.not(score: nil).count
    n_players_with_matching_score =  Player.where(score: self.score).count

    # Calculate percentage
    if total_players_with_score > 0
      percentage = (n_players_with_matching_score.to_f / total_players_with_score) * 100
      percentage_string = percentage.round.to_s
    else
      percentage_string = "0"
    end

    percentage_string
  end

end
