class DevicePool < Qt::Object

  private_class_method :new
  slots 'device_added(QString)'
  signals :webcam_added

  @@instance = nil

  def initialize(parent)
    super(parent)

    @sys_dbus = Qt::DBusConnection::system_bus

    @hal_service = "org.freedesktop.Hal"
    manager_path = "/org/freedesktop/Hal/Manager"
    manager_interface = "org.freedesktop.Hal.Manager"

    @hal_manager = Qt::DBusInterface.new(@hal_service, manager_path, manager_interface, @sys_dbus)

    @sys_dbus.connect(@hal_service, manager_path, manager_interface,
                     "DeviceAdded", self, SLOT('device_added(QString)'))

  end

  def device_added(uuid)
    emit webcam_added if is_webcam(uuid)
  end

  def is_webcam(uuid)
    hal_dev(uuid).call('QueryCapability', 'video4linux.video_capture').arguments[0].to_bool
  end

  def webcam?
    return webcams ? true : false
  end

  def webcams
    dev_list = @hal_manager.call("FindDeviceByCapability",
              "video4linux.video_capture").arguments[0].to_string_list

    webcams = {}

    dev_list.each do |uuid|
      hal_dev = hal_dev(uuid)

      dev = hal_dev.call("GetProperty", "video4linux.device").arguments[0].to_string
      name = hal_dev.call("GetProperty", "info.product").arguments[0].to_string
      webcams[dev] = name
    end

    return webcams.empty? ? nil : webcams
  end

  def hal_dev(uuid)
    Qt::DBusInterface.new(@hal_service, uuid, "org.freedesktop.Hal.Device", @sys_dbus)
  end

  def self.instance(parent = nil)
    return @@instance ? @@instance : new(parent)
  end

end

