# frozen_string_literal: true

# Dictionary class
class DictionariesController < ApplicationController
  before_action :authenticate_user!
  include ApplicationHelper
  before_action :check_access
  before_action :set_dictionary, only: %i[show edit update destroy]

  def check_access
    redirect_to not_found unless role?('dictionaries')
  end

  # GET /tags or /tags.json
  def index
    @dictionaries = Dictionary.all
  end

  # GET /tags/1 or /tags/1.json
  def show; end

  # GET /tags/new
  def new
    @dictionary = Dictionary.new
  end

  # GET /tags/1/edit
  def edit; end

  # POST /tags or /tags.json
  def create
    @dictionary = Dictionary.new(dictionary_params)

    respond_to do |format|
      if @dictionary.save
        format.html { redirect_to dictionaries_url, notice: 'Utworzono pomyślnie.' }
        format.json { render :show, status: :created, location: @dictionary }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @dictionary.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @dictionary.update(dictionary_params)
        format.html { redirect_to dictionaries_url, notice: 'Zaktualizowano pomyślnie.' }
        format.json { render :show, status: :ok, location: @dictionary }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @dictionary.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @dictionary.destroy

    respond_to do |format|
      format.html { redirect_to dictionaries_url, notice: 'Usunięto pomyślnie.' }
      format.json { head :no_content }
    end
  end

  private

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

  # Only allow a list of trusted parameters through.
  def dictionary_params
    params.require(:dictionary).permit(:shortcut, :name, :description)
  end
end
