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

    import android.content.Context
    import androidx.lifecycle.LiveData
    import androidx.lifecycle.MutableLiveData

    import dk.nsp.api.getBackendApiLayer
    import dk.nsp.domain.knowledge.Checklist
    import dk.nsp.domain.knowledge.ChecklistItem
    import dk.nsp.domain.knowledge.toDomainModel
    import dk.nsp.models.CheckListItem
    import dk.nsp.shared.*
    import dk.nsp.shared.util.asyncDefault
    import dk.nsp.shared.util.extensions.replace
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.Deferred

    class ChecklistRepository(
        context: Context
    ): ClearableRepository {
        private val configurationController = context.getBackendApiLayer().configurationController
        private val cmsController = context.getBackendApiLayer().cmsController

        private val _checklists: MutableLiveData<List<Checklist>> = MutableLiveData()
        val checklists: LiveData<List<Checklist>> = _checklists

        fun getChecklists(
            scope: CoroutineScope,
            episodeOfCareId: String
        ): Deferred<ResultWrapper<List<Checklist>>> =
            scope.asyncDefault {

                val checklistRes = cmsController.getChecklists(this).await()
                val checkedItems =
                    configurationController.getCheckedChecklistItems(this, episodeOfCareId).await()
                        .asSuccessValueOrNull()

                checklistRes.mapSuccess {
                    val domainModel = it.toDomainModel(checkedItems)

                    _checklists.postValue(domainModel)

                    domainModel
                }
            }

        fun clearChecklists(scope: CoroutineScope) = scope.asyncDefault {
            _checklists.postValue(null)
        }

        fun updateChecklistItem(
            scope: CoroutineScope,
            episodeOfCareId: String,
            checklist: Checklist,
            checklistItem: ChecklistItem
        ): Deferred<ResultWrapper<Unit>> = scope.asyncDefault {

            val updateChecklistItemRes = configurationController.updateChecklistItem(
                this,
                episodeOfCareId,
                checklist.id.toString(),
                CheckListItem(checklistItem.id, !checklistItem.value)
            ).await()

            when (updateChecklistItemRes) {
                is Success -> {
                    val updatedChecklistItem =
                        checklistItem.copy(value = updateChecklistItemRes.value.checked == true)

                    // Insert new copy of the checklistItem into the list
                    val copyOfChecklistItems = checklist.items.toMutableList()
                    val updatedListOfChecklistItems =
                        copyOfChecklistItems.replace(checklistItem, updatedChecklistItem)
                    val copyOfChecklist = checklist.copy(items = updatedListOfChecklistItems)

                    // Replace current list with new list
                    val updatedListOfChecklists =
                        _checklists.value?.toMutableList()?.replace(checklist, copyOfChecklist)
                    //Post updated list to our local LiveData
                    _checklists.postValue(updatedListOfChecklists)

                    Success(Unit)
                }
                is Failed -> {
                    Failed(Exception("Could not update checklist item ${checklistItem.id}"))
                }
            }
        }

        override fun clear() {
            _checklists.value = null
        }
    }