# EarlierVisitsRepository.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2023 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.core.data.repository.journal

    import dk.nsp.mingraviditet.core.data.domain.dueDates.DueDateDomainModel
    import dk.nsp.mingraviditet.core.data.domain.earlierVisits.EarlierVisitsDomainModel
    import dk.nsp.mingraviditet.core.data.domain.earlierVisits.toDomain
    import dk.nsp.mingraviditet.core.network.earlierVisits.EarlierVisitsDataSource
    import dk.nsp.mingraviditet.core.shared.network.Dispatcher
    import dk.nsp.mingraviditet.core.shared.network.Failed
    import dk.nsp.mingraviditet.core.shared.network.Loading
    import dk.nsp.mingraviditet.core.shared.network.MGDispatchers
    import dk.nsp.mingraviditet.core.shared.network.ResultWrapper
    import dk.nsp.mingraviditet.core.shared.network.Success
    import dk.nsp.mingraviditet.core.shared.network.mapSuccess
    import kotlinx.coroutines.CoroutineDispatcher
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.async
    import kotlinx.coroutines.coroutineScope
    import kotlinx.coroutines.flow.FlowCollector
    import kotlinx.coroutines.flow.MutableStateFlow
    import kotlinx.coroutines.flow.SharingStarted
    import kotlinx.coroutines.flow.StateFlow
    import kotlinx.coroutines.flow.combine
    import kotlinx.coroutines.flow.flowOn
    import kotlinx.coroutines.flow.stateIn
    import kotlinx.coroutines.flow.transformLatest
    import java.time.LocalDate
    import javax.inject.Inject
    import javax.inject.Singleton

    @Singleton
    class EarlierVisitsRepository @Inject constructor(
        private val earlierVisitsDataSource: EarlierVisitsDataSource,
        dueDatesRepository: DueDatesRepository,
        @Dispatcher(MGDispatchers.IO) private val ioDispatcher: CoroutineDispatcher,
    ) {

        val refreshTrigger = MutableStateFlow(0)

        val earlierVisits: StateFlow<ResultWrapper<EarlierVisitsDomainModel>> =
            combine(
                dueDatesRepository.selectableDueDates,
                refreshTrigger,
            ) { dueDates, refreshTrigger -> Pair(dueDates, refreshTrigger) }.transformLatest { it ->
                val dueDatesResult = it.first
                when (dueDatesResult) {
                    is Failed -> {
                        emit(Failed(dueDatesResult.error))
                    }

                    Loading -> {
                        emit(Loading)
                    }

                    is Success<List<DueDateDomainModel>> -> {
                        emitEarlierVisits(dueDatesResult)
                    }
                }
            }.flowOn(ioDispatcher)
                .stateIn(
                    scope = CoroutineScope(ioDispatcher),
                    started = SharingStarted.Lazily,
                    initialValue = Loading,
                )

        private suspend fun FlowCollector<ResultWrapper<EarlierVisitsDomainModel>>.emitEarlierVisits(
            it: Success<List<DueDateDomainModel>>,
        ) {
            val selectedDueDate = it.value.firstOrNull { it.selected }
            if (selectedDueDate == null) {
                Failed(Throwable("No selected due date found"))
                return
            }
            emit(Loading)
            val earlierVisits = coroutineScope {
                getEarlierVisits(selectedDueDate.date).await()
            }
            emit(earlierVisits)
        }

        private fun CoroutineScope.getEarlierVisits(dueDate: LocalDate) = async {
            with(earlierVisitsDataSource) {
                getEarlierVisits(dueDate).await().mapSuccess {
                    it.toDomain()
                }
            }
        }

        fun refreshEarlierVisits() {
            refreshTrigger.value += 1
        }
    }