class SpiritsController < ApplicationController
  include CalendarHelper

  before_action :set_spirit, only: %i[ show edit update destroy ]

  # GET /spirits or /spirits.json
  def index
    @spirits = Spirit.all
  end

  # GET /spirits/1 or /spirits/1.json
  def show
  end

  # GET /spirits/new
  def new
    @spirit = Spirit.new
  end

  # GET /spirits/1/edit
  def edit
  end

  def calendar
    start_date = params.fetch(:start_date, Date.today).to_date
    @events = Spirit.where(start_date: start_date.beginning_of_month.beginning_of_week..start_date.end_of_month.end_of_week)
  end

  # POST /spirits or /spirits.json
  def create
    @spirit = Spirit.new(spirit_params)

    respond_to do |format|
      if @spirit.save
        format.html { redirect_to spirit_url(@spirit), notice: "Spirit was successfully created." }
        format.json { render :show, status: :created, location: @spirit }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @spirit.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /spirits/1 or /spirits/1.json
  def update
    respond_to do |format|
      if @spirit.update(spirit_params)
        format.html { redirect_to spirit_url(@spirit), notice: "Spirit was successfully updated." }
        format.json { render :show, status: :ok, location: @spirit }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @spirit.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /spirits/1 or /spirits/1.json
  def destroy
    @spirit.destroy

    respond_to do |format|
      format.html { redirect_to spirits_url, notice: "Spirit was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_spirit
      @spirit = Spirit.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def spirit_params
      params.require(:spirit).permit(:name, :rank, :description, :abilities, :start_date, :end_date)
    end
end
