# ChecklistRepository.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

    import dk.nsp.mingraviditet.core.data.domain.knowledge.Checklist
    import dk.nsp.mingraviditet.core.data.domain.knowledge.ChecklistItem
    import dk.nsp.mingraviditet.core.data.domain.knowledge.toDbModel
    import dk.nsp.mingraviditet.core.data.domain.knowledge.toDomainModel
    import dk.nsp.mingraviditet.core.datastore.MGPreferencesDataSource
    import dk.nsp.mingraviditet.core.datastore.PregnancyPreferencesDataSource
    import dk.nsp.mingraviditet.core.datastore.model.ChecklistDb
    import dk.nsp.mingraviditet.core.network.cms.CMSDataSource
    import dk.nsp.mingraviditet.core.shared.network.Dispatcher
    import dk.nsp.mingraviditet.core.shared.network.MGDispatchers
    import dk.nsp.mingraviditet.core.shared.network.asSuccessValueOrNull
    import kotlinx.coroutines.CoroutineDispatcher
    import kotlinx.coroutines.flow.Flow
    import kotlinx.coroutines.flow.flow
    import kotlinx.coroutines.flow.flowOn
    import kotlinx.coroutines.flow.map
    import kotlinx.coroutines.withContext
    import javax.inject.Inject
    import javax.inject.Singleton

    @Singleton
    class ChecklistRepository @Inject constructor(
        private val cmsDataSource: CMSDataSource,
        private val pregnancyDataSource: PregnancyPreferencesDataSource,
        private val preferencesDataSource: MGPreferencesDataSource,
        @Dispatcher(MGDispatchers.IO) private val ioDispatcher: CoroutineDispatcher,
    ) {

        fun getChecklists(): Flow<List<Checklist>?> = flow {
            pregnancyDataSource.checklists.map {
                it.toList().map(ChecklistDb::toDomainModel)
            }.collect { localChecklists ->
                if (localChecklists.isEmpty()) {
                    val remoteChecklists = cmsDataSource.getChecklists()
                    val remote = remoteChecklists.asSuccessValueOrNull()

                    remote?.let { pregnancyDataSource.setChecklists(it.toDbModel()) }

                    emit(remote?.toDomainModel())
                } else {
                    emit(localChecklists)
                }
            }
        }.flowOn(ioDispatcher)

        val shouldShowDeleteChecklistItemAnimation = preferencesDataSource.shouldShowChecklistItemDeleteAnimation

        suspend fun recoverChecklist(id: Int) = withContext(ioDispatcher) {
            val recoveredChecklist = cmsDataSource.getChecklists().asSuccessValueOrNull()?.firstOrNull { it.id == id }

            recoveredChecklist?.let {
                pregnancyDataSource.setChecklist(it.toDbModel())
            }
        }

        suspend fun toggle(item: ChecklistItem) = withContext(ioDispatcher) {
            pregnancyDataSource.toggleCheckedChecklistItem(item.toDbModel())
        }

        suspend fun update(checklistId: Int, item: ChecklistItem) = withContext(ioDispatcher) {
            pregnancyDataSource.updateChecklistItem(checklistId, item.toDbModel())
        }

        suspend fun delete(checklistId: Int, item: ChecklistItem) = withContext(ioDispatcher) {
            pregnancyDataSource.deleteChecklistItem(checklistId, item.toDbModel())
        }

        suspend fun incrementChecklistItemDeleteAnimationShownCount() =
            withContext(ioDispatcher) { preferencesDataSource.incrementChecklistItemDeleteAnimationShownCount() }

        suspend fun disableChecklistItemDeleteAnimation() = withContext(ioDispatcher) { preferencesDataSource.disableChecklistItemDeleteAnimation() }
    }