# frozen_string_literal: true
module Panel
  #
  module Crud
    extend ActiveSupport::Concern

    included do
      respond_to :html
      before_action :set_item, only: [:show, :edit, :update, :destroy]
      before_action :set_uniq_institution!, only: [:update]

      helper_method :model
    end

    def index
      respond_to do |format|
        format.json { super }
        format.csv  { super }
        format.html { respond_to_html }
      end
    end

    def respond_to_html
      add_breadcrumb t('home'), panel_root_url
      add_breadcrumb humanized_model_name(:many), index_url
      render template: 'concerns/panel/index'
    end

    def new
      @item = model.new

      init_form
      breadcrumbs_for(:new)
      render template: 'concerns/panel/form'
    end

    def create
      @item = model.new item_params
      set_uniq_institution!
      return redirect_to(edit_url, flash: { saved: true }) if @item.save

      init_form
      breadcrumbs_for(:new)
      render template: 'concerns/panel/form'
    end

    def edit
      init_form
      breadcrumbs_for(:edit)

      render template: 'concerns/panel/form'
    end

    def update
      respond_to do |format|
        format.json { super }
        format.html do
          return redirect_to(edit_url, flash: { saved: true }) if
            @item.update_attributes(item_params)

          breadcrumbs_for(:edit)
          init_form
          render template: 'concerns/panel/form'
        end
      end
    end

    def destroy
      if @item.destroy
        redirect_to index_url, flash: { destroyed: true }
      else
        redirect_to index_url, flash: { destroyed: false, errors: @item.errors.full_messages }
      end
    end

    def init_form
    end

    def set_uniq_institution!
      return unless @item.respond_to? :institution_id
      #return unless current_user.one_institution?
      @item.institution_id = current_user.uniq_institution.try(:id)
    end

    private

    def item_params
      perms = params.require(:item).permit(permits)
      #perms.delete(:institution_id) if current_user.one_institution?
      perms
    end

    def set_item
      @item = if model.respond_to?(:friendly)
                model.friendly.find params[:id]
              else
                model.find params[:id]
              end
    end

    def show_url
      url_for(action: :show, id: @item)
    end

    def edit_url
      url_for(action: :edit, id: @item)
    end

    def index_url
      url_for(controller: model.to_s.underscore.pluralize, action: :index)
    end

    def humanized_model_name(count = 1)
      t(model.to_s.underscore, scope: 'activerecord.models', count: count)
    end

    def breadcrumbs_for(action)
      add_breadcrumb t('home'), panel_root_url
      add_breadcrumb humanized_model_name(count: :many), index_url
      add_breadcrumb t(action.to_s), nil
    end
  end
end
