# frozen_string_literal: true

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

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

    # GET /admin/weeks/1
    # GET /admin/weeks/1.json
    def show; end

    # GET /admin/weeks/new
    def new
      @week = Week.new(course_id: params[:course_id])
    end

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

    # POST /admin/weeks
    # POST /admin/weeks.json
    def create
      @week = Week.new(admin_week_params)
      @course = @week.course
      params[:course_id] = @course.id
      respond_to do |format|
        if @week.save
          format.js { collection }
          format.html do
            redirect_to [:admin, @week],
                        notice: 'Week was successfully created.'
          end
          format.json { render :show, status: :created, location: @week }
        else
          format.js { render :new }
          format.html { render :new }
          format.json do
            render json: @week.errors, status: :unprocessable_entity
          end
        end
      end
    end

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

    # DELETE /admin/weeks/1
    # DELETE /admin/weeks/1.json
    def destroy
      @week.destroy
      respond_to do |format|
        format.js { collection }
        format.html do
          redirect_to admin_weeks_url,
                      notice: 'Week was successfully destroyed.'
        end
        format.json { head :no_content }
      end
    end

    private

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

    def collection
      @weeks = Week.by_course(params[:course_id]).page(params[:page])
      @course = Course.find(params[:course_id])
    end

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