1 /*
<lambda>null2  * Copyright (C) 2022 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.wallpaper.picker.undo.ui.binder
19 
20 import android.app.Dialog
21 import android.widget.Toolbar
22 import androidx.lifecycle.Lifecycle
23 import androidx.lifecycle.LifecycleOwner
24 import androidx.lifecycle.lifecycleScope
25 import androidx.lifecycle.repeatOnLifecycle
26 import com.android.wallpaper.R
27 import com.android.wallpaper.picker.common.dialog.ui.viewbinder.DialogViewBinder
28 import com.android.wallpaper.picker.common.dialog.ui.viewmodel.DialogViewModel
29 import com.android.wallpaper.picker.undo.ui.viewmodel.UndoViewModel
30 import kotlinx.coroutines.launch
31 
32 object RevertToolbarButtonBinder {
33     /** Binds the given view to the given view-model. */
34     fun bind(
35         view: Toolbar,
36         viewModel: UndoViewModel,
37         lifecycleOwner: LifecycleOwner,
38     ) {
39         val menuItem = view.menu.findItem(R.id.revert)
40         menuItem.setOnMenuItemClickListener {
41             viewModel.onRevertButtonClicked()
42             true
43         }
44 
45         var dialog: Dialog? = null
46 
47         fun showDialog(viewModel: DialogViewModel) {
48             dialog =
49                 DialogViewBinder.show(
50                     context = view.context,
51                     viewModel = viewModel,
52                     dialogStyleResourceId = R.style.ResetDialogTheme,
53                 )
54             dialog?.show()
55         }
56 
57         fun dismissDialog() {
58             dialog?.setOnDismissListener(null)
59             dialog?.dismiss()
60             dialog = null
61         }
62 
63         lifecycleOwner.lifecycleScope.launch {
64             lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
65                 launch { viewModel.isRevertButtonVisible.collect { menuItem.isVisible = it } }
66 
67                 launch {
68                     viewModel.dialog.collect { dialogViewModel ->
69                         if (dialogViewModel != null) {
70                             dismissDialog()
71                             showDialog(dialogViewModel)
72                         } else {
73                             dismissDialog()
74                         }
75                     }
76                 }
77             }
78         }
79     }
80 }
81