package rasel.lunar.launcher.utils

import io.realm.kotlin.ext.query
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import rasel.lunar.launcher.home.LauncherHome.Companion.lastedFinishedPageUrl
import rasel.lunar.launcher.model.MostItem
import rasel.lunar.launcher.model.RssData
import rasel.lunar.launcher.model.RssDataType
import rasel.lunar.launcher.model.dateFormat
import rasel.lunar.launcher.model.getRssData
import rasel.lunar.launcher.workers.WorkersDb
import java.nio.charset.Charset
import java.text.SimpleDateFormat
import java.util.Base64
import java.util.Date

val USAGT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15"
fun String.getJ() = Jsoup.connect(this).userAgent(USAGT).get()
object FeedParseManager {
    val parsers = listOf<SoInterface>(QVZTb2dpcmw,SkFWTW9zdA)
    fun parse(doc : Document, consoleLog : (String)-> Unit) {
        consoleLog("FeedParseManager START")
        try {
            parsers.filter { doc.title().contains(it.getName()) }.first()?.let {
                it.parse(doc,consoleLog)
            }
        } catch (e : Exception) {
            consoleLog(e.message ?: "Exception")
            e.printStackTrace()
        }
        consoleLog("FeedParseManager END")
    }
}
interface SoInterface{
    fun getName() : String
    fun parse(doc : Document, consoleLog : (String)-> Unit)
}
object QVZTb2dpcmw : SoInterface {
    override fun getName(): String {
        return String(Base64.getMimeDecoder().decode(this.javaClass.simpleName.plus("==").toByteArray()))
    }
    override fun parse(doc : Document, consoleLog : (String)-> Unit) {
        doc.getElementsByTag("article").forEach { article ->
            consoleLog("ogirl article >>> ${article.text()}")
            val title = article.getElementsByTag("a").get(0).attr("title")
            val href = article.getElementsByTag("a").get(0).attr("href")
            val img = article.getElementsByTag("img").get(0).attr("data-src")
            WorkersDb.getRealm().writeBlocking {
                if (query<RssData>("originPage == $0", href).find().size == 0) {
                    RssData().apply {
                        this.originPage = href
                        this.title = title
                        this.description = "Sogirl"
                        this.thumbnail = img
                        this.pubDate = Date().time
                        this.category = RssDataType.GURU.name
                        this.chosung =
                            JamoUtils.split(title).joinToString("")
                        copyToRealm(this)
                    }
                    consoleLog("title $title | href $href | img $img" )
                }
            }
        }
    }
}
object SkFWTW9zdA : SoInterface {
    var dmy = SimpleDateFormat("dd-MM-yyyy")
    override fun getName(): String {
        return String(Base64.getMimeDecoder().decode(this.javaClass.simpleName.plus("==").toByteArray()))
    }
    override fun parse(doc: Document, consoleLog: (String) -> Unit) {
        consoleLog("$lastedFinishedPageUrl >>> ${doc.title()}")
        doc.getElementsByClass("card").forEach { card ->
            var thumb = if(card.getElementsByTag("img").size > 0) card.getElementsByTag("img").get(0).attr("src") else ""
            if (thumb.contains("No+Poster")) thumb = if(card.getElementsByTag("img").size > 0) card.getElementsByTag("img").get(0).attr("data-src") else thumb
            var model = if(card.getElementsByTag("img").size > 0) card.getElementsByTag("img").get(0).attr("alt") else ""
            if(card.getElementsByClass("card-block").size > 0) if(card.getElementsByClass("card-block").size > 0) {
                val link = card.getElementsByClass("card-block").get(0).getElementsByTag("a").get(0).attr("href")
                val title = card.getElementsByClass("card-block").get(0).getElementsByTag("a").get(0).attr("title")
                val date  = card.getElementsByTag("span").get(0).text()
                MostItem().let { ms ->
                    ms.model = model
                    ms.image = thumb
                    ms.pageLink = link
                    ms.title = title
                    try {
                        ms.date = dmy.parse(date).time
                        consoleLog("dateFormat.format(Date(ms.date)) ${dateFormat.format(Date(ms.date))}")
                    }catch (e : Exception) {e.printStackTrace()}
                    if (ms.isValid()) {
                        WorkersDb.insertData(ms.getRssData())
                    }
                }
                consoleLog(" model >>>>> ${model}\n | thumb >>>>> ${thumb}\n | title >>>>> ${title}\n | date >>>>> ${date} | ")
            }
        }
        consoleLog("excuted j req() ${WorkersDb.getRealm().query<RssData>("category == $0", RssDataType.GURU.name).find().size}")
    }
}