module Keys
  class ConfigurationsController < Keys::BaseController
    def index
      authorize Keys::Configuration

      @key_pool_metadata = []
      unless params[:pool_id].present?
        flash[:error] = 'Pool ID is required'
        return
      end

      @pool_id = params[:pool_id]

      cursor = ''
      if params[:cursor].present?
        cursor = params[:cursor]
      end

      resp = Configuration.all(@pool_id, cursor, current_user.ldap_login)
      unless resp.success? && resp.status == 200
        flash[:error] = 'Error loading key pool metadata'
        return
      end

      unless resp.body['key_pool_metadata'].nil?
        @key_pool_metadata = resp.body['key_pool_metadata']
      end
      @cursor = resp.body['cursor']
      @metadata = Configuration.new
    end

    def create
      authorize Configuration

      @metadata = Configuration.new
      permitted = params.require(:keys_configuration).permit(:pool_id, :metadata_key, :metadata_value).merge(ldap_login: current_user.ldap_login)
      @metadata.attributes = permitted

      resp = @metadata.create
      unless resp.success? && resp.status == 200
        flash[:error] = 'Error creating metadata'
        return redirect_back
      end

      flash[:success] = 'Successfully created metadata'

      redirect_back
    end

    def delete
      authorize Configuration

      permitted = params.permit(:pool_id, :metadata_key).merge(ldap_login: current_user.ldap_login)
      @metadata = Configuration.from_attributes(permitted)
      resp = @metadata.delete

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error deleting metadata'
        return redirect_back
      end

      flash[:success] = 'Successfully deleted metadata'

      redirect_back
    end
  end
end
