# frozen_string_literal: true
module Panel
  #
  class UsersController < PanelController
    before_action :check_admin
    include Panel::Crud
    include Panel::Multiple


    def model
      User
    end

    def permits
      [
        :name, :email, :password, :password_confirmation, :administrative_area,
        institution_ids: [], branch_ids: [], role_attributes: [:name]
      ]
    end

    def init_form
      if current_user.has_role?("admin")
        @institutions = Institution.order(Institution.acts_as_label)
        @allowed_roles = Role.where.not(name: 'oir_local').pluck(:name)
        @branches = Branch.accessible_by(current_ability).order(:name)
      elsif current_user.has_role?("oir_local")
        @allowed_roles = Role.where(name: ['administrative_unit']).pluck(:name)
        @institutions = Institution.where("id IN (?)", current_user.institution_ids)
      else
        @allowed_roles = Role.where.not(name: 'admin').pluck(:name)
        @institutions = Institution.where("id IN (?)", current_user.institution_ids)
      end
      @branches = Branch.accessible_by(current_ability).order(:name)
      @roles = action_name == "edit" ? User.find(params[:id]).roles.first : nil
    end

    def respond_to_json
      @q = User.accessible_by(current_ability)
      @q = @q.ransack(params[:filter])
      @c = @q.result.paginate(page: params[:page], per_page: params[:count])

      render json: json_result(@c)
    end

    def create
      @item = model.new item_params
      set_uniq_institution!
      if @item.save
        @item.add_role(params[:role])
        unless current_user.has_role?(:admin)
          @item.institutions << current_user.uniq_institution
          @item.branches << current_user.branches
        end
        return redirect_to(edit_url, flash: { saved: true })
      end
      init_form
      breadcrumbs_for(:new)
      render template: 'concerns/panel/form'
    end

    def update
      @item.attributes = item_params
      m = @item.password.blank? ? :update_without_password : :update_attributes
      if @item.send(m, item_params)
        if @item.roles.blank?
          @item.add_role(params[:role])
        else
          @item.roles = []
          @item.add_role(params[:role])
        end
        return redirect_to(edit_url, flash: { saved: true })
      end
      breadcrumbs_for(:edit)
      init_form
      render template: 'concerns/panel/form'
    end

    private

    def check_admin
      if current_user.has_role?("administrative_unit")
        redirect_to panel_root_url
      end
    end

    def json_methods
      [ :roles_name_s, :institutions_name, :branches_name ]
    end

  end
end
