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

module Debci
  class Backend
    # Select which backend to use for the given package. The backend specified
    # in the package `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(package, arch)
      candidates = backend_list.dup
      if package.backend && candidates.first != package.backend
        candidates.unshift(package.backend)
      end

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

      selected || default
    end

    def self.backend_list
      Debci.config.backend_list
    end

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