package it.unisannio.ding.ids.wedroid.app.data.repository import android.util.Log import androidx.lifecycle.LiveData import it.unisannio.ding.ids.wedroid.app.data.dao.WListDao import it.unisannio.ding.ids.wedroid.app.data.entity.WList import it.unisannio.ding.ids.wedroid.app.data.entity.convert import it.unisannio.ding.ids.wedroid.app.util.PreferenceReader import it.unisannio.ding.ids.wedroid.wrapper.api.ListService import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import retrofit2.Call import retrofit2.Callback import retrofit2.Response class WListRepository( private val dao: WListDao, private val service: ListService, private val reader: PreferenceReader ) { val allWLists: LiveData> by lazy { dao.allWList } init { synchronize() } fun synchronize() { service.getAllList(reader.boardId) .enqueue(object : Callback> { override fun onFailure( call: Call>, t: Throwable ) = logNetworkError(t.message) override fun onResponse( call: Call>, response: Response> ) { CoroutineScope(Dispatchers.IO).launch { synchronizeCallback(response) } } }) } private fun synchronizeCallback( response: Response> ) { if (!response.isSuccessful) { logNetworkError("${response.code()} ${response.message()}") return } val wLists = (response.body() ?: return) .map { it.convert() } addNewWListToDb(wLists) removeOldWListsFromDb(wLists) } fun deleteWList(idBoard: String, idWList: String) { service.deleteList(idBoard, idWList).enqueue( object : Callback { override fun onFailure( call: Call, t: Throwable ) { logNetworkError(t.message) } override fun onResponse( call: Call, response: Response ) { CoroutineScope(Dispatchers.IO).launch { deleteWListCallBack(response, idWList) } } }) } private fun deleteWListCallBack( response: Response, id: String ) { if (!response.isSuccessful) { logNetworkError("${response.code()} ${response.message()}") return } dao.delete(WList(id)) } private fun addNewWListToDb(wLists: Collection) { wLists.forEach { dao.insert(it) } } private fun removeOldWListsFromDb(wLists: Collection) { allWLists.value?.minus(wLists) ?.forEach { dao.delete(it) } } @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") private fun logNetworkError(message: String?) { Log.e("RETROFIT", message) } }