# JournalMeasurementsViewModel.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.journal.sections.measurements

    import androidx.hilt.Assisted
    import androidx.lifecycle.MutableLiveData
    import androidx.lifecycle.Observer
    import androidx.lifecycle.SavedStateHandle
    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.domain.repository.ObservationsRepository
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.ui.adapterviews.KeyValueData
    import dk.nsp.mingraviditet.ui.adapterviews.KeyValueRow
    import dk.nsp.mingraviditet.ui.adapterviews.KeyValueSectionHeader
    import dk.nsp.mingraviditet.ui.main.journal.extensions.toTextModel
    import dk.nsp.mingraviditet.ui.main.journal.extensions.toTextModelWithoutUnit
    import dk.nsp.mingraviditet.ui.main.journal.sections.JournalCommonDialogNavigatorViewModel
    import dk.nsp.mingraviditet.ui.main.journal.sections.measurements.bll.toPubismeasurementLineChartData
    import dk.nsp.mingraviditet.ui.main.journal.sections.measurements.chart.models.LineChartSetupData
    import dk.nsp.mingraviditet.ui.main.journal.sections.measurements.table.models.common.TableColumnSet
    import dk.nsp.mingraviditet.ui.main.journal.sections.measurements.table.models.measurement.ObservationMeasurementTableData
    import dk.nsp.mingraviditet.util.android.recycler.RecyclerAdapterView
    import dk.nsp.mingraviditet.util.extensions.getValue
    import dk.nsp.mingraviditet.util.extensions.toSingleEvent
    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.shared.util.launchDefault
    import dk.nsp.util.TextModel
    import kotlinx.coroutines.CoroutineScope
    import timber.log.Timber
    import javax.inject.Inject

    @HiltViewModel
    class JournalMeasurementsViewModel @Inject constructor(
        private val dataCardRepository: DataCardRepository,
        private val dictionaryRepository: DictionaryRepository,
        private val observationsRepository: ObservationsRepository,
        @Assisted private val savedStateHandle: SavedStateHandle
    ) : JournalCommonDialogNavigatorViewModel() {

        private val _tableData = MutableLiveData<TableColumnSet?>()
        val tableData by _tableData

        private val _bodyRows = MutableLiveData<List<RecyclerAdapterView<*>>>()
        val bodyRows = _bodyRows

        private val _onDictionary = MutableLiveData<SingleEvent<DictionaryEntry>>()
        val onDictionary by _onDictionary

        private val _lineChartData = MutableLiveData<LineChartSetupData>()
        val lineChartData by _lineChartData

        private val observationObserver =
            Observer<DataCard?> { currentDataCard: DataCard? ->
                currentDataCard?.let {
                    _bodyRows.postValue(getBodyMeasurementRows(it))
                    getClinicalObservationsFromRepository(it.episodeOfCareIdentifier)
                }
            }

        init {
            dataCardRepository.currentDataCard.observeForever(observationObserver)
        }

        override fun onCleared() {
            super.onCleared()
            dataCardRepository.currentDataCard.removeObserver(observationObserver)
        }

        private fun getClinicalObservationsFromRepository(episodeOfCareIdentifier: String) {
            viewModelScope.launchDefault {

                val observationsRes =
                    observationsRepository.getClinicalObservationsAsync(
                        viewModelScope,
                        episodeOfCareIdentifier
                    ).await()

                when (observationsRes) {
                    is Success -> {
                        val observations = observationsRes.value
                        val tableData = ObservationMeasurementTableData(observations).toTableColumnSet(
                            ::dictionaryCallback,
                            ::triggerNavigateToActivity,
                            ::triggerNavigateToInfo
                        )
                        _tableData.postValue(tableData)

                        _lineChartData.postValue(observations.toPubismeasurementLineChartData())
                    }
                    is Failed -> {
                        _tableData.postValue(null)
                        Timber.e(observationsRes.error)
                    }
                }
            }
        }

        private fun dictionaryCallback(key: TextModel) =
            getDictionaryEntryFor(viewModelScope, key)?.let {
                {
                    _onDictionary.postValue(it.toSingleEvent())
                }
            }

        private fun getDictionaryEntryFor(scope: CoroutineScope, key: TextModel) =
            dictionaryRepository.getDictionaryEntryFor(scope, key)

        private fun getBodyMeasurementRows(maternityDataCard: DataCard): List<RecyclerAdapterView<*>> {
            val bodySection = maternityDataCard.bodyMeasuresSection

            val weightBeforeMaternityKey =
                TextModel.from(R.string.journal_section_measurements_weight_before_maternity_value_title)
            val heightBeforeMaternityKey =
                TextModel.from(R.string.journal_section_measurements_height_before_maternity_value_title)
            val bmiBeforeMaternityKey =
                TextModel.from(R.string.journal_section_measurements_bmi_before_maternity_value_title)

            return listOf(
                KeyValueSectionHeader(
                    TextModel.from(R.string.journal_section_measurements_weight_before_maternity_title)
                ),
                KeyValueRow(
                    KeyValueData(
                        weightBeforeMaternityKey,
                        bodySection?.prenatalBodyWeight.toTextModel(),
                        null,
                        dictionaryCallback(weightBeforeMaternityKey)
                    )
                ),
                KeyValueRow(
                    KeyValueData(
                        heightBeforeMaternityKey,
                        bodySection?.bodyHeight.toTextModel(),
                        null,
                        dictionaryCallback(heightBeforeMaternityKey)
                    )
                ), KeyValueRow(
                    KeyValueData(
                        bmiBeforeMaternityKey,
                        bodySection?.bodyMassIndex.toTextModelWithoutUnit(),
                        null,
                        dictionaryCallback(bmiBeforeMaternityKey)
                    )
                )
            )
        }
    }