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

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import ru.fincode.tsudesk.core.network.model.NetworkResult
import ru.fincode.tsudesk.feature.news.data.remote.datasource.NewsRemoteDataSource
import ru.fincode.tsudesk.feature.news.data.remote.parser.NewsHtmlParser
import ru.fincode.tsudesk.feature.news.domain.model.NewsItem
import ru.fincode.tsudesk.feature.news.domain.repository.NewsRepository
import javax.inject.Inject

class NewsRepositoryImpl @Inject constructor(
    private val remote: NewsRemoteDataSource,
    private val parser: NewsHtmlParser
) : NewsRepository {

    override fun loadPage(page: Int): Flow<NetworkResult<List<NewsItem>>> = flow {
        when (val result = remote.loadArchivePageHtml(page)) {
            is NetworkResult.Success -> {
                val items = parser.parseArchivePage(result.data)
                emit(NetworkResult.Success(items, result.meta))
            }
            is NetworkResult.Error -> emit(result)
        }
    }.flowOn(Dispatchers.IO)
}