# ChangeDataCardViewModel.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2021 The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of
     * this software and associated documentation files (the "Software"), to deal in
     * the Software without restriction, including without limitation the rights to
     * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
     * of the Software, and to permit persons to whom the Software is furnished to do
     * so, subject to the following conditions:
     *
     *
     * The above copyright notice and this permission notice shall be included in all
     * copies or substantial portions of the Software.
     *
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     * SOFTWARE.
     */

    package dk.nsp.mingraviditet.ui.main.overview.change_datacard

    import androidx.lifecycle.LiveData
    import androidx.lifecycle.MutableLiveData
    import androidx.lifecycle.ViewModel
    import androidx.lifecycle.viewModelScope
    import com.commonsense.android.kotlin.base.extensions.collections.categorizeInto
    import com.commonsense.android.kotlin.base.extensions.coroutines.launchDefault
    import com.commonsense.android.kotlin.base.extensions.coroutines.launchIO
    import dagger.hilt.android.lifecycle.HiltViewModel
    import dk.nsp.domain.repository.DataCardRepository
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.ui.adapterviews.ErrorStateRow
    import dk.nsp.mingraviditet.ui.common.SectionHeaderAdapterView
    import dk.nsp.mingraviditet.util.android.recycler.RecyclerAdapterView
    import dk.nsp.mingraviditet.util.extensions.postSingleEvent
    import dk.nsp.mingraviditet.util.livedata.SingleEvent
    import dk.nsp.models.DataCard
    import dk.nsp.shared.Failed
    import dk.nsp.shared.Success
    import dk.nsp.util.TextModel
    import dk.nsp.util.isActive
    import dk.nsp.util.isEnded
    import javax.inject.Inject

    @HiltViewModel
    class ChangeDataCardViewModel @Inject constructor(
        private val dataCardRepository: DataCardRepository
    ) : ViewModel() {

        private val _rowsToShow = MutableLiveData<List<RecyclerAdapterView<*>>>()
        val rowsToShow: LiveData<List<RecyclerAdapterView<*>>> = _rowsToShow

        private val _dismissBottomSheet = MutableLiveData<SingleEvent<Unit>>()
        val dismissButtonSheet: LiveData<SingleEvent<Unit>> = _dismissBottomSheet

        private val _showLoadingSpinner = MutableLiveData<Unit>()
        val showLoadingSpinner: LiveData<Unit> = _showLoadingSpinner

        init {
            updateDataCardRows()
        }

        private fun updateDataCardRows() {
            viewModelScope.launchIO {
                _showLoadingSpinner.postValue(Unit)
                when (val dataCardsRes = dataCardRepository.getDataCards(this).await()) {
                    is Failed -> {
                        _rowsToShow.postValue(
                            listOf(
                                ErrorStateRow(
                                    description = TextModel.from(
                                        R.string.overview_pick_pregnancy_none
                                    )
                                )
                            )
                        )
                    }
                    is Success -> {
                        val currentDataCard = dataCardRepository.currentDataCard.value

                        val (active, ended) = dataCardsRes.value.categorizeInto(
                            { it.isActive },
                            { it.isEnded })

                        val rows = mutableListOf<RecyclerAdapterView<*>>().apply {
                            addAll(
                                createDataCardsSection(
                                    R.string.overview_pick_pregnancy_active_section,
                                    currentDataCard,
                                    active
                                )
                            )
                            addAll(
                                createDataCardsSection(
                                    R.string.overview_pick_pregnancy_ended_section,
                                    currentDataCard,
                                    ended
                                )
                            )
                        }

                        _rowsToShow.postValue(rows)
                    }
                }
            }
        }

        private fun onDataCardSelected(selectedDataCard: DataCard) =
            viewModelScope.launchDefault {
                val res = dataCardRepository.setDataCard(this, selectedDataCard).await()
                if (res is Failed) {
                    updateDataCardRows()
                }

                _dismissBottomSheet.postSingleEvent()
            }

        private fun createDataCardsSection(
            sectionTitle: Int,
            currentDataCard: DataCard?,
            dataCards: List<DataCard>
        ): List<RecyclerAdapterView<*>> {
            val sectionRows = mutableListOf<RecyclerAdapterView<*>>()
            sectionRows.add(SectionHeaderAdapterView(TextModel.from(sectionTitle)))

            val dataCardRows = dataCards.map { dataCard ->
                ChangeDataCardChooserRow(
                    ChangeDataCardChooserViewBindingModel(
                        dataCard,
                        currentDataCard == dataCard
                    ) {
                        _showLoadingSpinner.postValue(Unit)
                        onDataCardSelected(dataCard)
                    })
            }

            if (dataCardRows.isEmpty()) {
                sectionRows.add(ChangeDataCardEmptyStateRow(TextModel.Companion.from(R.string.overview_pick_pregnancy_none)))
            } else {
                sectionRows.addAll(dataCardRows)
            }

            return sectionRows
        }
    }