# frozen_string_literal: true

module Admin
  # Kursy
  class CoursesController < ApplicationController
    before_action :set_object, only: %i[show edit update destroy]

    # GET /admin/courses
    # GET /admin/courses.json
    def index
      collection
    end

    # GET /admin/courses/1
    # GET /admin/courses/1.json
    def show
      @weeks = @course.weeks.page(params[:page])
    end

    # GET /admin/courses/new
    def new
      @course = Course.new
    end

    # GET /admin/courses/1/edit
    def edit; end

    # POST /admin/courses
    # POST /admin/courses.json
    def create
      @course = Course.new(admin_course_params)

      respond_to do |format|
        if @course.save
          format.js { collection }
          format.html { redirect_to [:admin, @course], notice: 'Course was successfully created.' }
          format.json { render :show, status: :created, location: @course }
        else
          format.js { render :new }
          format.html { render :new }
          format.json { render json: @course.errors, status: :unprocessable_entity }
        end
      end
    end

    # PATCH/PUT /admin/courses/1
    # PATCH/PUT /admin/courses/1.json
    def update
      respond_to do |format|
        if @course.update(admin_course_params)
          format.js { collection }
          format.html { redirect_to [:admin, @course], notice: 'Course was successfully updated.' }
          format.json { render :show, status: :ok, location: @course }
        else
          format.js { render :edit }
          format.html { render :edit }
          format.json { render json: @course.errors, status: :unprocessable_entity }
        end
      end
    end

    # DELETE /admin/courses/1
    # DELETE /admin/courses/1.json
    def destroy
      @course.destroy
      respond_to do |format|
        format.js { collection }
        format.html { redirect_to admin_courses_url, notice: 'Course was successfully destroyed.' }
        format.json { head :no_content }
      end
    end

    private

    # Use callbacks to share common setup or constraints between actions.
    def set_object
      @course = Course.find(params[:id])
    end

    def collection
      @courses = Course.name_asc.page(params[:page])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def admin_course_params
      params.require(:course).permit(:name, :description)
    end
  end
end
