# frozen_string_literal: true
module Admin
  class QuizController < AdminController
    def index
      @quizzes = policy_scope Quiz.all
    end

    def new
      authorize Quiz
      @quiz = Quiz.new
    end

    def create
      authorize Quiz
      @quiz = Quiz.create(quiz_params)

      if @quiz.persisted?
        redirect_to admin_quizzes_path, flash: { notice: "Sucessfully created quiz" }
      else
        flash[:error] = "Failed to save quiz."
        render :new
      end
    end

    def view
      @quiz = Quiz.find(params[:quiz_id])
      authorize @quiz
    end

    def edit
      @quiz = Quiz.find(params[:quiz_id])
      authorize @quiz
    end

    def update
      @quiz = Quiz.find(params[:quiz_id])
      authorize @quiz

      if @quiz.update_attributes(quiz_params)
        redirect_to admin_quiz_path(@quiz.to_i),
                    flash: { notice: "Sucessfully updated quiz" }
      else
        flash[:error] = "Failed to update quiz."
        render :edit
      end
    end

    private

      def quiz_params
        params.require(:quiz).permit(:name, :dept, :unit)
      end
  end
end
