2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.spotify.internal.handler;
15 import java.util.HashMap;
16 import java.util.List;
18 import java.util.stream.Collectors;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.openhab.binding.spotify.internal.api.model.Device;
22 import org.openhab.binding.spotify.internal.api.model.Playlist;
23 import org.openhab.core.thing.ChannelUID;
24 import org.openhab.core.thing.binding.BaseDynamicStateDescriptionProvider;
25 import org.openhab.core.thing.type.DynamicStateDescriptionProvider;
26 import org.openhab.core.types.StateOption;
27 import org.osgi.service.component.annotations.Component;
30 * Dynamically create the users list of devices and playlists.
32 * @author Hilbrand Bouwkamp - Initial contribution
34 @Component(service = { DynamicStateDescriptionProvider.class, SpotifyDynamicStateDescriptionProvider.class })
36 public class SpotifyDynamicStateDescriptionProvider extends BaseDynamicStateDescriptionProvider {
38 private final Map<ChannelUID, List<Device>> devicesByChannel = new HashMap<>();
39 private final Map<ChannelUID, List<Playlist>> playlistsByChannel = new HashMap<>();
41 public void setDevices(ChannelUID channelUID, List<Device> spotifyDevices) {
42 final List<Device> devices = devicesByChannel.get(channelUID);
44 if (devices == null || (spotifyDevices.size() != devices.size()
45 || !spotifyDevices.stream().allMatch(sd -> devices.stream().anyMatch(
46 d -> sd.getId() == d.getId() && d.getName() != null && d.getName().equals(sd.getName()))))) {
47 devicesByChannel.put(channelUID, spotifyDevices);
48 setStateOptions(channelUID, spotifyDevices.stream()
49 .map(device -> new StateOption(device.getId(), device.getName())).collect(Collectors.toList()));
53 public void setPlayLists(ChannelUID channelUID, List<Playlist> spotifyPlaylists) {
54 final List<Playlist> playlists = playlistsByChannel.get(channelUID);
56 if (playlists == null || (spotifyPlaylists.size() != playlists.size() || !spotifyPlaylists.stream()
57 .allMatch(sp -> playlists.stream().anyMatch(p -> p.getUri() != null && p.getUri().equals(sp.getUri())
58 && p.getName() != null && p.getName().equals(sp.getName()))))) {
59 playlistsByChannel.put(channelUID, spotifyPlaylists);
60 setStateOptions(channelUID,
61 spotifyPlaylists.stream().map(playlist -> new StateOption(playlist.getUri(), playlist.getName()))
62 .collect(Collectors.toList()));
67 public void deactivate() {
69 devicesByChannel.clear();
70 playlistsByChannel.clear();