class CandidateController < ApplicationController
  def welcome
  end

  def question
    @status = QuizStatus.new(current_candidate)
    qid = @status.current_question_id

    redirect_to :summary and return if qid.nil?

    @question = current_candidate.fetch_question(qid)
    @answer = Answer.new
  end

  def update_answer
    answer_ids = { question_id: answer_params[:question_id], candidate_id: current_candidate.to_i }
    @answer = Answer.find_or_create_by!(answer_ids)
    @answer.answer = answer_for_type
    @answer.saved = answer_params[:save]
    @answer.submitted = answer_params[:next]

    if @answer.save
      redirect_to :summary and return if params.key?(:update)
      redirect_to :saved and return if params.key?(:save)
      redirect_to :question
    else
      flash[:error] = [answer_params[:question_id]]
      @question = current_candidate.fetch_question(qid)
      render :question
    end
  end

  def summary
    @quiz = current_candidate.my_quiz
    @status = QuizStatus.new(current_candidate)

    redirect_to :question and return unless @status.current_question_id.nil?
  end

  def update_summary
    redirect_to :summary
  end

  def thankyou
    redirect_to root_path if session[:test_id].nil?
    reset_session
  end

  def saved
  end

  def validate
    candidate = Candidate.find_by(test_hash: params['test_id'])

    if candidate.nil?
      reset_session
      redirect_to root_path, alert: "Sorry, incorrect test id"
    else
      session[:test_id] = candidate.test_hash
      redirect_to :question
    end
  end

  def live_coder
    @question = Question.find(params[:question_id])
    @answer = @question.answers.order("RAND()").first.answer
    render layout: false
  end

  private

    def answer_params
      params.require(:answer).permit(
        :question_id, :answer_id,
        :save, :next, :summary,
        :radio, :text, checkbox: [], live_coder: []
      )
    end

    def answer_for_type
      return answer_params[:radio] unless answer_params[:radio].nil?
      return answer_params[:text] unless answer_params[:text].nil?
      return answer_params[:checkbox] unless answer_params[:checkbox].nil?
      return answer_params[:live_coder] unless answer_params[:live_coder].nil?
    end
end
