require 'debci/amqp'
require 'debci/config'

module Debci
  class Backend
    # Select which backend to use, given a preferred backend and the target
    # architecture. The backend specified in the `backend` attribute will be
    # used if that backend is available for the given architecture; otherwise,
    # the configured backend list is searched, and if no available backend if
    # found, the default backend is used as a fallback. The default backend is
    # assumed to be available.
    def self.select(backend, arch)
      return default unless backend

      candidates = backend_list.dup
      if backend && candidates.first != backend
        candidates.unshift(backend)
      end

      selected = candidates.find do |candidate|
        Debci::AMQP.queue_exists?(arch, candidate)
      end

      selected || default
    end

    def self.backend_list
      Debci.config.backend_list
    end

    def self.default
      Debci.config.backend
    end
  end
end
