1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.tv.settings.library.data;
18 
19 import android.util.ArrayMap;
20 
21 import com.android.tv.settings.library.PreferenceCompat;
22 
23 import java.util.Map;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
26 
27 /** Manage the creation and removal of {@link PreferenceCompat} for a state. */
28 public class PreferenceCompatManager {
29     private final Map<String, PreferenceCompat> mPrefCompats = new ArrayMap<>();
30 
getOrCreatePrefCompat(String key)31     public PreferenceCompat getOrCreatePrefCompat(String key) {
32         return getOrCreatePrefCompat(new String[]{key});
33     }
34 
35     /**
36      * Get or create the preferenceCompat with the specified key.
37      *
38      * @param key key of the preferenceCompat
39      * @return preferenceCompat with the specified key.
40      */
getOrCreatePrefCompat(String[] key)41     public PreferenceCompat getOrCreatePrefCompat(String[] key) {
42         if (key == null) {
43             return null;
44         }
45         String compoundKey = getKey(key);
46         if (!mPrefCompats.containsKey(compoundKey)) {
47             mPrefCompats.put(compoundKey, new PreferenceCompat(key));
48         }
49         return mPrefCompats.get(compoundKey);
50     }
51 
52     /**
53      * Get the preferenceCompat, used in
54      * {@link PreferenceControllerState#onPreferenceChange(String[],
55      * Object)}
56      * or {@link PreferenceControllerState#onPreferenceTreeClick(String[], boolean)}
57      *
58      * @param key key of the preferenceCompat
59      * @return preferenceCompat with the specified key, or null if does not exist.
60      */
getPrefCompat(String[] key)61     public PreferenceCompat getPrefCompat(String[] key) {
62         if (key == null) {
63             return null;
64         }
65         String compoundKey = getKey(key);
66         return mPrefCompats.get(compoundKey);
67     }
68 
getKey(String[] key)69     public static String getKey(String[] key) {
70         return Stream.of(key).collect(Collectors.joining(" "));
71     }
72 }
73