package ru.fincode.tsudesk.feature.news.data.datasource

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import ru.fincode.tsudesk.core.network.apiCall
import ru.fincode.tsudesk.core.network.model.NetworkResult
import ru.fincode.tsudesk.core.network.model.map
import ru.fincode.tsudesk.feature.news.data.parser.NewsArchiveHtmlParser
import ru.fincode.tsudesk.feature.news.data.remote.api.NewsApi
import javax.inject.Inject

class NewsArchiveDataSource @Inject constructor(
    private val api: NewsApi,
    private val parser: NewsArchiveHtmlParser
) {

    suspend fun loadPage(page: Int): NetworkResult<NewsArchiveHtmlParser.ParsedPage> =
        withContext(Dispatchers.IO) {
            apiCall { api.getNewsArchive(page = page) }
                .map { body, _ ->
                    val html = body.string()
                    parser.parse(html = html, currentPage = page)
                }
        }
}