# JournalNotesViewModel.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.notes

    import androidx.lifecycle.LiveData
    import androidx.lifecycle.MutableLiveData
    import androidx.lifecycle.Observer
    import androidx.lifecycle.ViewModel
    import androidx.lifecycle.viewModelScope
    import dagger.hilt.android.lifecycle.HiltViewModel
    import dk.nsp.domain.repository.DataCardRepository
    import dk.nsp.domain.repository.NotesRepository
    import dk.nsp.mingraviditet.R
    import dk.nsp.mingraviditet.ui.adapterviews.DetailsHeaderRow
    import dk.nsp.mingraviditet.ui.adapterviews.EmptyStateFullHeight
    import dk.nsp.mingraviditet.ui.adapterviews.ErrorStateFullHeight
    import dk.nsp.mingraviditet.ui.adapterviews.FoldableCardData
    import dk.nsp.mingraviditet.ui.main.journal.JournalSection
    import dk.nsp.mingraviditet.ui.widgets.HeaderViewWithIconBindingModel
    import dk.nsp.mingraviditet.util.android.recycler.RecyclerAdapterView
    import dk.nsp.mingraviditet.util.extensions.getTitleTextModel
    import dk.nsp.models.DataCard
    import dk.nsp.models.Note
    import dk.nsp.shared.Failed
    import dk.nsp.shared.Success
    import dk.nsp.shared.util.launchDefault
    import dk.nsp.util.TextModel
    import javax.inject.Inject

    @HiltViewModel
    class JournalNotesViewModel @Inject constructor(
        private val notesRepository: NotesRepository,
        private val dataCardRepository: DataCardRepository
    ) : ViewModel() {

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

        private val episodeOfCareObserver =
            Observer<DataCard?> { currentDataCard: DataCard? ->
                currentDataCard?.let {
                    getNotes(it.episodeOfCareIdentifier)
                }
            }

        init {
            dataCardRepository.currentDataCard.observeForever(episodeOfCareObserver)
        }

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

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

                when (val notesRes =
                    notesRepository.getNotes(viewModelScope, episodeOfCareIdentifier).await()) {
                    is Success -> {
                        if (notesRes.value.isNotEmpty()) {
                            _rowsToShow.postValue(createRows(notesRes.value))
                        } else {
                            _rowsToShow.postValue(
                                listOf(
                                    EmptyStateFullHeight(
                                        TextModel.from(R.string.journal_section_journal_notes_empty_title),
                                        TextModel.from(R.string.journal_section_journal_notes_empty_description)
                                    )
                                )
                            )
                        }
                    }
                    is Failed -> {
                        // Empty state
                        _rowsToShow.postValue(
                            listOf(
                                ErrorStateFullHeight(
                                    TextModel.from(R.string.common_alert_title_error),
                                    TextModel.from(R.string.common_alert_message_failed_to_load_data)
                                )
                            )
                        )
                    }
                }
            }
        }

        private fun createRows(notes: List<Note>): List<RecyclerAdapterView<*>> {
            val rows = mutableListOf<RecyclerAdapterView<*>>()

            rows.add(
                DetailsHeaderRow(
                    HeaderViewWithIconBindingModel(
                        JournalSection.JournalNotes.getTitle(),
                        JournalSection.JournalNotes.getDescription(),
                        JournalSection.JournalNotes.getIcon()
                    )
                )
            )

            val noteRows = notes.map {
                JournalNoteCardRow(
                    FoldableCardData(
                        it.date,
                        it.getTitleTextModel(),
                        TextModel.Companion.from(it.content)
                    ),
                    it
                )
            }

            rows.addAll(noteRows)

            return rows
        }
    }