module QuizHelperMethods
  extend ActiveSupport::Concern

  included do
    before_action :require_player!
    before_action :set_locale

    helper_method :current_player,
                  :questions,
                  :question,
                  :questions_size,
                  :question_index,
                  :player_question_answer,
                  :result_node

  end


private


  def questions
    @questions ||= Node.at_depth(1).tmpl_article.viewable.ordered.to_a
  end

  def result_node
    @result_node ||= Node.at_depth(1).tmpl_list.viewable.first
  end


  def question
    @question ||= questions[params[:id].to_i-1]
  end


  def player_question_answer
    @player_question_answer ||= Answer.find_by(player_id: current_player.id, node_id: question.id)&.value
  end


  def questions_size
    @questions_size ||= questions.size
  end


  def question_index
    @question_index ||= (params[:id].to_i)
  end


  def require_player!
    unless player_present?
      redirect_to url_for(controller: 'players', action: 'new')
    end
  end


  def current_player
    Current.player ||= player_from_session
  end


  def player_from_session
    Player.find_by(id: session[:player_id])
  end


  def player_present?
    current_player.present?
  end


end
