# frozen_string_literal: true

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

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

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

    # GET /admin/lessons/new
    def new
      @lesson = Lesson.new(week_id: params[:week_id])
    end

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

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

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

    # DELETE /admin/lessons/1
    # DELETE /admin/lessons/1.json
    def destroy
      @lesson.destroy
      respond_to do |format|
        format.js { collection }
        format.html do
          redirect_to admin_lessons_url,
                      notice: 'Lesson 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
      @lesson = Lesson.find(params[:id])
      @week = @lesson.week
      params[:week_id] = @week.id
    end

    def collection
      @lessons = Lesson.by_week(params[:week_id]).page(params[:page])
      @week = Week.find(params[:week_id])
    end

    # Never trust parameters from the scary internet,
    # only allow the white list through.
    def admin_lesson_params
      params.require(:lesson).permit(:name, :description, :week_id, :video_id,
                                     :informations)
    end
  end
end
