module OauthClients
  class ItemsController < OauthClients::BaseController
    before_action :set_item, only: [:show, :edit, :update, :destroy]

    def index
      authorize Item

      filter_params = filter_get_params
      if filter_params[:client_id].present?
        return redirect_to oauth_clients_item_path(filter_params[:client_id].strip)
      end

      @items, @cursor = Item.all(filter_params)
    end

    def show
    end

    def new
      @item = Item.new
      authorize @item
    end

    def create
      @item = Item.create(current_user.ldap_login, create_params)
      authorize @item
      if @item.errors.empty?
        flash[:success] = "Success"
        render :show
      else
        flash.now[:danger] = @item.errors.full_messages.to_sentence
        render :new
      end
    end

    def edit
    end

    def update
      @item.attributes = update_params
      if @item.update(current_user.ldap_login)
        flash[:success] = "Success"
        return redirect_to oauth_clients_item_path(@item)
      else
        flash.now[:danger] = @item.errors.full_messages.to_sentence
        render :edit
      end
    end

    def destroy
      if @item.destroy(current_user.ldap_login)
        flash[:success] = "Success"
      else
        flash[:error] = @item.errors.full_messages.to_sentence
      end

      redirect_back
    end

    protected

    def set_item
      @item = Item.find params[:id]
      unless @item.errors.empty?
        flash[:error] = @item.errors.full_messages.to_sentence
        return redirect_to oauth_clients_items_path
      end
      authorize @item
    end

    def create_params
      params.require(:oauth_clients_item).permit(:name, :owner_id, :redirect_uri, :category)
    end

    def update_params
      update_params = params.require(:oauth_clients_item).permit(
        :id, :client_id,
        :owner_id, :redirect_uri, :category,
        :name, :password_grant_allowed,
        :should_expire_tokens, :allow_embed, :is_fuel_client, :is_first_party, :hidden
      )
      boolean_keys = [:allow_embed, :should_expire_tokens, :password_grant_allowed, :is_fuel_client, :is_first_party, :hidden]
      boolean_keys.each do |key|
        update_params[key] = Service::Base.booleanize(update_params[key])
      end
      update_params
    end

    def filter_get_params
      return {} unless params['item'].present?
      params['item'].permit(:id, :client_id, :owner_id, :name, :sort_key, :sort_order, :cursor)
    end
  end
end
