# PreviousAbortionsViewModel.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2020 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.journal.sections.sectiondetails.aroundthepregnancy.previouspregnancies

    import androidx.lifecycle.LiveData
    import androidx.lifecycle.MutableLiveData
    import androidx.lifecycle.ViewModel
    import androidx.lifecycle.viewModelScope
    import dagger.hilt.android.lifecycle.HiltViewModel
    import dk.nsp.domain.dictionary.DictionaryEntry
    import dk.nsp.domain.repository.DataCardRepository
    import dk.nsp.domain.repository.DictionaryRepository
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.ui.adapterviews.EmptyStateFullHeight
    import dk.nsp.mingraviditet.ui.adapterviews.TableHeaderRow
    import dk.nsp.mingraviditet.ui.adapterviews.TableRow
    import dk.nsp.mingraviditet.ui.adapterviews.TableRowBindingModel
    import dk.nsp.mingraviditet.ui.main.journal.extensions.toTextModel
    import dk.nsp.mingraviditet.util.android.recycler.RecyclerAdapterView
    import dk.nsp.mingraviditet.util.extensions.toSingleEvent
    import dk.nsp.mingraviditet.util.extensions.toTextModelOrDefault
    import dk.nsp.mingraviditet.util.extensions.transform
    import dk.nsp.mingraviditet.util.livedata.SingleEvent
    import dk.nsp.models.PreviousAbortionsSectionAllOfAbortions
    import dk.nsp.util.TextModel
    import kotlinx.coroutines.CoroutineScope
    import javax.inject.Inject

    @HiltViewModel
    class PreviousAbortionsViewModel @Inject constructor(
        dataCardRepository: DataCardRepository,
        private val dictionaryRepository: DictionaryRepository,
    ) : ViewModel() {

        private val _onDictionaryClicked: MutableLiveData<SingleEvent<DictionaryEntry>> =
            MutableLiveData()
        val onDictionaryClicked: LiveData<SingleEvent<DictionaryEntry>> = _onDictionaryClicked

        val previousAbortions = dataCardRepository.currentDataCard.transform {
            val abortions = it?.previousAbortionsSection?.abortions ?: emptyList()
            if (abortions.isNotEmpty()) {
                createRows(abortions)
            } else {
                createEmptyState()
            }
        }

        private fun createRows(previousAbortions: List<PreviousAbortionsSectionAllOfAbortions>): List<RecyclerAdapterView<*>> {
            return previousAbortions.mapIndexed { index, abortion ->
                createAbortionSection(index, previousAbortions.size == 1, abortion)
            }.flatten()
        }

        private fun createAbortionSection(
            index: Int,
            singleItem: Boolean,
            abortion: PreviousAbortionsSectionAllOfAbortions
        ): List<RecyclerAdapterView<*>> {
            val abortionYearKey =
                TextModel.from(R.string.journal_section_previous_abortions_abortion_year)
            val gestationLengthKey =
                TextModel.from(R.string.journal_section_previous_abortions_abortion_gestation_length)
            val abortionTypeKey =
                TextModel.from(R.string.journal_section_previous_abortions_abortion_type)
            val indicationKey =
                TextModel.from(R.string.journal_section_previous_abortions_abortion_indication)

            val abortionGestationValue = abortion.gestationLength?.value?.let {
                if (it != 0) {
                    val weeks = it / 7
                    val days = it % 7
                    "$weeks+$days"
                } else {
                    "0"
                }
            }

            return listOf(
                TableHeaderRow(
                    TextModel.from(
                        R.string.journal_section_previous_abortions_abortion_title,
                        TextModel.from(if (singleItem) "" else (index + 1).toString())
                    )
                ),
                TableRow(
                    TableRowBindingModel(
                        abortionYearKey,
                        abortion.year.toString().toTextModelOrDefault(),
                        0,
                        getDictionaryCallback(abortionYearKey)
                    )
                ),
                TableRow(
                    TableRowBindingModel(
                        gestationLengthKey,
                        abortionGestationValue.toTextModelOrDefault(),
                        1,
                        getDictionaryCallback(gestationLengthKey)
                    )
                ),
                TableRow(
                    TableRowBindingModel(
                        abortionTypeKey,
                        abortion.type.toTextModel(),
                        2,
                        getDictionaryCallback(abortionTypeKey)
                    )
                ),
                TableRow(
                    TableRowBindingModel(
                        indicationKey,
                        abortion.indication.toTextModelOrDefault(),
                        3,
                        getDictionaryCallback(indicationKey)
                    )
                )
            )
        }

        private fun createEmptyState(): List<RecyclerAdapterView<*>> {
            return listOf(
                EmptyStateFullHeight(
                    TextModel.from(R.string.journal_section_previous_abortions_empty_state_title),
                    TextModel.from(R.string.journal_section_previous_abortions_empty_state_description)
                )
            )
        }

        private fun getDictionaryCallback(forKey: TextModel): (() -> Unit)? {
            return getDictionaryEntryFor(
                viewModelScope,
                forKey
            )?.let { { _onDictionaryClicked.postValue(it.toSingleEvent()) } }
        }

        private fun getDictionaryEntryFor(scope: CoroutineScope, key: TextModel): DictionaryEntry? {
            return dictionaryRepository.getDictionaryEntryFor(scope, key)
        }
    }