package bou.amine.apps.readerforselfossv2.utils

import android.net.Uri
import android.text.Html
import bou.amine.apps.readerforselfossv2.model.SelfossModel
import org.jsoup.Jsoup
import java.util.*

actual fun String.getHtmlDecoded(): String {
    return Html.fromHtml(this).toString()
}

actual fun SelfossModel.Item.getIcon(baseUrl: String): String {
    return constructUrl(baseUrl, "favicons", icon)
}

actual fun SelfossModel.Item.getThumbnail(baseUrl: String): String {
    return constructUrl(baseUrl, "thumbnails", thumbnail)
}

actual fun SelfossModel.Item.getImages(): ArrayList<String> {
    val allImages = ArrayList<String>()

    for (image in Jsoup.parse(content).getElementsByTag("img")) {
        val url = image.attr("src")
        if (url.lowercase(Locale.US).contains(".jpg") ||
            url.lowercase(Locale.US).contains(".jpeg") ||
            url.lowercase(Locale.US).contains(".png") ||
            url.lowercase(Locale.US).contains(".webp")
        ) {
            allImages.add(url)
        }
    }
    return allImages
}

actual fun SelfossModel.Source.getIcon(baseUrl: String): String {
    return constructUrl(baseUrl, "favicons", icon)
}

actual fun constructUrl(
    baseUrl: String,
    path: String,
    file: String?,
): String {
    return if (file == null || file == "null" || file.isEmpty()) {
        ""
    } else {
        val baseUriBuilder = Uri.parse(baseUrl).buildUpon()
        baseUriBuilder.appendPath(path).appendPath(file)

        baseUriBuilder.toString()
    }
}
