package bou.amine.apps.readerforselfossv2.rest

import bou.amine.apps.readerforselfossv2.model.*
import io.github.aakira.napier.Napier
import io.ktor.client.*
import io.ktor.client.plugins.cache.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json

class MercuryApi() {

    var client = createHttpClient()

    private fun createHttpClient(): HttpClient {
        return HttpClient {
            install(ContentNegotiation) {
                install(HttpCache)
                json(Json {
                    prettyPrint = true
                    isLenient = true
                    ignoreUnknownKeys = true
                })
            }
            install(Logging) {
                logger = object : Logger {
                    override fun log(message: String) {
                        Napier.d(message, tag = "LogMercuryCalls")
                    }
                }
                level = LogLevel.INFO
            }
            expectSuccess = false
        }
    }

    suspend fun query(url: String): StatusAndData<MercuryModel.ParsedContent> =
        bodyOrFailure(client.get("https://amine-louveau.fr/parser.php") {
            parameter("link", url)
        })
}