# RetrofitCMSDataSource.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2023 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.mingraviditet.core.network.cms

    import dk.nsp.mingraviditet.core.network.cms.models.NetworkArticleCategory
    import dk.nsp.mingraviditet.core.network.cms.models.NetworkChecklist
    import dk.nsp.mingraviditet.core.network.cms.models.NetworkFAQItem
    import dk.nsp.mingraviditet.core.network.cms.models.NetworkPage
    import dk.nsp.mingraviditet.core.network.cms.models.NetworkRecommendedArticles
    import dk.nsp.mingraviditet.core.network.cms.models.NetworkRedirectArticle
    import dk.nsp.mingraviditet.core.network.cms.models.NetworkSearchResult
    import dk.nsp.mingraviditet.core.shared.network.Dispatcher
    import dk.nsp.mingraviditet.core.shared.network.MGDispatchers
    import dk.nsp.mingraviditet.core.shared.network.ResultWrapper
    import dk.nsp.mingraviditet.core.shared.network.tryOrFailed
    import kotlinx.coroutines.CoroutineDispatcher
    import kotlinx.coroutines.withContext
    import retrofit2.Retrofit
    import timber.log.Timber
    import java.net.HttpURLConnection
    import java.net.URL
    import javax.inject.Inject
    import javax.inject.Singleton

    @Singleton
    class RetrofitCMSDataSource @Inject constructor(
        retrofit: Retrofit,
        @Dispatcher(MGDispatchers.IO) private val ioDispatcher: CoroutineDispatcher,
    ) : CMSDataSource {

        private val cmsApi = retrofit.create(CMSApi::class.java)

        override suspend fun getFAQ(): ResultWrapper<List<NetworkFAQItem>> = tryOrFailed { cmsApi.getFAQ() }

        override suspend fun getArticleSections(): ResultWrapper<List<NetworkArticleCategory>> = tryOrFailed { cmsApi.getArticles() }

        override suspend fun getAfterBirthArticleCategories(afterBirthWeek: Int): ResultWrapper<NetworkRecommendedArticles> =
            tryOrFailed { cmsApi.getAfterBirthArticleCategories(afterBirthWeek) }

        override suspend fun getArticleCategories(week: Int): ResultWrapper<NetworkRecommendedArticles> = tryOrFailed { cmsApi.getArticleCategories(week) }

        override suspend fun searchArticles(query: String): ResultWrapper<List<NetworkSearchResult>> = tryOrFailed { cmsApi.search(query) }

        override suspend fun getChecklists(): ResultWrapper<List<NetworkChecklist>> = tryOrFailed { cmsApi.getChecklists() }

        override suspend fun getPageContent(pagePath: String): ResultWrapper<NetworkPage> = tryOrFailed {
            cmsApi.getPageContentFor(pagePath)
        }

        @Suppress("BlockingMethodInNonBlockingContext")
        override suspend fun getRedirectLink(url: String): String = withContext(ioDispatcher) {
            Timber.i("Get redirect link from $url")
            val internalLinkUrl = URL(url)
            val urlConnection: HttpURLConnection = internalLinkUrl.openConnection() as HttpURLConnection
            urlConnection.instanceFollowRedirects = false
            val redirectPath = urlConnection.getHeaderField("location")
            Timber.i("Redirect path -> $redirectPath")
            redirectPath
        }

        override suspend fun getRedirectArticle(id: Int): ResultWrapper<NetworkRedirectArticle> = tryOrFailed {
            cmsApi.getLinkedArticle(id)
        }
    }