# PreviousBirthsViewModel.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.hilt.Assisted
    import androidx.lifecycle.LiveData
    import androidx.lifecycle.MutableLiveData
    import androidx.lifecycle.SavedStateHandle
    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.KeyValueData
    import dk.nsp.mingraviditet.ui.adapterviews.KeyValueRow
    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.ui.main.journal.extensions.toTextModelWithoutUnit
    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.PreviousBirthsSectionAllOfBirths
    import dk.nsp.models.PreviousBirthsSectionAllOfChildren
    import dk.nsp.util.TextModel
    import kotlinx.coroutines.CoroutineScope
    import javax.inject.Inject

    @HiltViewModel
    class PreviousBirthsViewModel @Inject constructor(
        dataCardRepository: DataCardRepository,
        private val dictionaryRepository: DictionaryRepository,
        @Assisted private val savedStateHandle: SavedStateHandle
    ) : ViewModel() {

        val previousBirths = dataCardRepository.currentDataCard.transform {
            val births = it?.previousBirthsSection?.births ?: emptyList()
            if (births.isNotEmpty()) {
                createRows(births)
            } else {
                createEmptyState()
            }
        }

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

        private fun createRows(previousBirths: List<PreviousBirthsSectionAllOfBirths>): List<RecyclerAdapterView<*>> {
            return previousBirths.map {
                createRowsForBirth(it)
            }.flatten()
        }

        private fun createRowsForBirth(birth: PreviousBirthsSectionAllOfBirths): List<RecyclerAdapterView<*>> {
            val birthSection = mutableListOf<RecyclerAdapterView<*>>()

            val childSections = birth.children?.mapIndexed { index, child ->
                createRowsForChild(index, birth, child)
            }?.flatten()

            childSections?.let(birthSection::addAll)

            val gestationLengthKey =
                TextModel.from(R.string.journal_section_previous_births_child_gestation_length)
            val birthYearKey = TextModel.from(R.string.journal_section_previous_births_child_year)
            val placeOfBirthKey =
                TextModel.from(R.string.journal_section_previous_births_child_place_of_birth)
            val subjectiveExperienceKey =
                TextModel.from(R.string.journal_section_previous_births_child_subjective_experience)
            val pregnancySummaryKey =
                TextModel.from(R.string.journal_section_previous_births_pregnancy_summary)
            val birthSummaryKey = TextModel.from(R.string.journal_section_previous_births_birth_summary)
            val puerperalSepsisSummaryKey =
                TextModel.from(R.string.journal_section_previous_births_puerperal_sepsis_summary)

            val birthRows = listOf(
                KeyValueRow(
                    KeyValueData(
                        birthYearKey,
                        birth.year?.toString().toTextModelOrDefault(),
                        null,
                        getDictionaryCallback(birthYearKey)
                    )
                ),
                KeyValueRow(
                    KeyValueData(
                        gestationLengthKey,
                        birth.gestationLength.toTextModelWithoutUnit(),
                        null,
                        getDictionaryCallback(gestationLengthKey)
                    )
                ),
                KeyValueRow(
                    KeyValueData(
                        placeOfBirthKey,
                        birth.birthPlace.toTextModelOrDefault(),
                        null,
                        getDictionaryCallback(placeOfBirthKey)
                    )
                ),
                KeyValueRow(
                    KeyValueData(
                        subjectiveExperienceKey,
                        birth.subjectiveBirthExperience.toTextModel(),
                        null,
                        getDictionaryCallback(subjectiveExperienceKey)
                    )
                ),
                KeyValueRow(
                    KeyValueData(
                        pregnancySummaryKey,
                        birth.pregnancySummary.toTextModelOrDefault(),
                        null,
                        getDictionaryCallback(pregnancySummaryKey)
                    )
                ),
                KeyValueRow(
                    KeyValueData(
                        birthSummaryKey,
                        birth.birthSummary.toTextModelOrDefault(),
                        null,
                        getDictionaryCallback(birthSummaryKey)
                    )
                ),
                KeyValueRow(
                    KeyValueData(
                        puerperalSepsisSummaryKey,
                        birth.puerperalSepsis.toTextModelOrDefault(),
                        null,
                        getDictionaryCallback(puerperalSepsisSummaryKey)
                    )
                )
            )

            birthSection.addAll(birthRows)

            return birthSection
        }

        private fun createRowsForChild(
            index: Int,
            birth: PreviousBirthsSectionAllOfBirths,
            child: PreviousBirthsSectionAllOfChildren
        ): List<RecyclerAdapterView<*>> {
            val sexKey = TextModel.from(R.string.journal_section_previous_births_child_sex)

            val weightKey = TextModel.from(R.string.journal_section_previous_births_child_weight)
            val outcomeKey = TextModel.from(R.string.journal_section_previous_births_child_outcome)
            val currentHealthKey =
                TextModel.from(R.string.journal_section_previous_births_child_current_health)

            return listOf<RecyclerAdapterView<*>>(
                TableHeaderRow(
                    TextModel.from(
                        R.string.journal_section_previous_births_child_title,
                        TextModel.from(if (birth.children?.size == 1) "" else (index + 1).toString())
                    )
                ),
                TableRow(
                    TableRowBindingModel(
                        sexKey,
                        child.sex.toTextModel(),
                        0,
                        getDictionaryCallback(sexKey)
                    )
                ),
                TableRow(
                    TableRowBindingModel(
                        weightKey,
                        child.birthWeight.toTextModel(),
                        1,
                        getDictionaryCallback(weightKey)
                    )
                ),
                TableRow(
                    TableRowBindingModel(
                        outcomeKey,
                        child.outcome.toTextModel(),
                        2,
                        getDictionaryCallback(outcomeKey)
                    )
                ),
                TableRow(
                    TableRowBindingModel(
                        currentHealthKey,
                        child.childsCurrentHealthStatus.toTextModelOrDefault(),
                        3,
                        getDictionaryCallback(currentHealthKey)
                    )
                )
            )
        }

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

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

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