1 /*
<lambda>null2  * Copyright (C) 2023 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 
18 package com.android.customization.picker.grid.domain.interactor
19 
20 import android.util.Log
21 import com.android.customization.picker.grid.shared.model.GridOptionItemModel
22 import com.android.wallpaper.picker.undo.domain.interactor.SnapshotRestorer
23 import com.android.wallpaper.picker.undo.domain.interactor.SnapshotStore
24 import com.android.wallpaper.picker.undo.shared.model.RestorableSnapshot
25 
26 class GridSnapshotRestorer(
27     private val interactor: GridInteractor,
28 ) : SnapshotRestorer {
29 
30     private var store: SnapshotStore = SnapshotStore.NOOP
31     private var originalOption: GridOptionItemModel? = null
32 
33     override suspend fun setUpSnapshotRestorer(store: SnapshotStore): RestorableSnapshot {
34         this.store = store
35         val option = interactor.getSelectedOption()
36         originalOption = option
37         return snapshot(option)
38     }
39 
40     override suspend fun restoreToSnapshot(snapshot: RestorableSnapshot) {
41         val optionNameFromSnapshot = snapshot.args[KEY_GRID_OPTION_NAME]
42         originalOption?.let { optionToRestore ->
43             if (optionToRestore.name != optionNameFromSnapshot) {
44                 Log.wtf(
45                     TAG,
46                     """Original snapshot name was ${optionToRestore.name} but we're being told to
47                         | restore to $optionNameFromSnapshot. The current implementation doesn't
48                         | support undo, only a reset back to the original grid option."""
49                         .trimMargin(),
50                 )
51             }
52 
53             interactor.setSelectedOption(optionToRestore)
54         }
55     }
56 
57     fun store(option: GridOptionItemModel) {
58         store.store(snapshot(option))
59     }
60 
61     private fun snapshot(option: GridOptionItemModel?): RestorableSnapshot {
62         return RestorableSnapshot(
63             args =
64                 buildMap {
65                     option?.name?.let { optionName -> put(KEY_GRID_OPTION_NAME, optionName) }
66                 }
67         )
68     }
69 
70     companion object {
71         private const val TAG = "GridSnapshotRestorer"
72         private const val KEY_GRID_OPTION_NAME = "grid_option"
73     }
74 }
75