package com.example.myapplication.api.repository

import com.example.myapplication.database.entities.Category
import com.example.myapplication.database.repository.CategoryRepository
import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.model.toCategory
import com.example.myapplication.database.repository.OfflineCategoryRepository


class RestCategoryRepository(
    private val service: MyServerService,
    private val dbCategoryRepository: OfflineCategoryRepository,
): CategoryRepository {
    override suspend fun getAll(): List<Category> {
        val existCategories = dbCategoryRepository.getAll().associateBy { it.id }.toMutableMap()

        kotlin.runCatching {
            service.getCategories()
                .map { it.toCategory() }
                .forEach { category ->
                    val existCategory = existCategories[category.id]
                    if (existCategory == null) {
                        dbCategoryRepository.insert(category)
                    }
                    existCategories[category.id] = category
                }
        }
            .onFailure {

            }
        return existCategories.map { it.value }.sortedBy { it.id }
    }

    override suspend fun insert(category: Category) {
        TODO("Not yet implemented")
    }
}