package bou.amine.apps.readerforselfossv2.android.model

import android.content.Context
import android.webkit.URLUtil
import bou.amine.apps.readerforselfossv2.model.SelfossModel
import bou.amine.apps.readerforselfossv2.utils.getImages
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions

fun SelfossModel.Item.preloadImages(context: Context) : Boolean {
    val imageUrls = this.getImages()

    val glideOptions = RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL).timeout(10000)


    try {
        for (url in imageUrls) {
            if ( URLUtil.isValidUrl(url)) {
                Glide.with(context).asBitmap()
                    .apply(glideOptions)
                    .load(url).submit()
            }
        }
    } catch (e : Error) {
        return false
    }

    return true
}

fun String.toTextDrawableString(): String {
    val textDrawable = StringBuilder()
    for (s in this.split(" ".toRegex()).filter { it.isNotEmpty() }.toTypedArray()) {
        try {
            textDrawable.append(s[0])
        } catch (e: StringIndexOutOfBoundsException) {
            // We do nothing
        }
    }
    return textDrawable.toString()
}