class QuestionsController < ApplicationController

  include QuizHelperMethods


  def show
    not_found unless question

    @answer = Answer.find_or_initialize_by(player_id: current_player.id, node_id: question.id)
  end


  def answer
    @answer = Answer.find_by(node_id: question.id, player_id: current_player.id)
    @question_answer = question.attachments.with_text.each_slice(2).to_a[@answer.value]
  end


  def score

    not_found if result_node.blank? or current_player.answers.count < questions.size

    planet_score = 0

    current_player.answers.ordered.each_with_index do |answer, i|
      case i
      when 0, 3
        planet_score += 1 if answer.value == 0
      else
        planet_score += 1 if answer.value == 1
      end
    end

    current_player.update(score: planet_score)

    quiz_result = QuizResult.create!(
      player_name: current_player.name,
      score: planet_score,
      stats: current_player.stats,
      locale: I18n.locale
    )

    redirect_to url_for(action: 'result', sid: quiz_result.share_id)

  end



  def result
    not_found if result_node.blank? or current_player.score.blank?

    people_score = questions.count - current_player.score
    score_diff = people_score - current_player.score

    attachment_index =  case
                        when score_diff >= 2
                          0 # People
                        when score_diff <= -2
                          1 # Planet
                        else
                          2 # Balanced
                        end

    @result_attachment = result_node.attachments.offset(attachment_index).first
    @stats_attachment = result_node.attachments.offset(3).first

  end


  def shared_result

    @quiz_result = QuizResult.find_by!(share_id: params[:id])

    people_score = questions.count - @quiz_result.score
    score_diff = people_score - @quiz_result.score

    attachment_index =  case
                        when score_diff >= 2
                          0 # People
                        when score_diff <= -2
                          1 # Planet
                        else
                          2 # Balanced
                        end

    @result_attachment = result_node.attachments.offset(attachment_index).first
    @stats_attachment = result_node.attachments.offset(3).first

  end




end
