package rasel.lunar.launcher.workers

import android.annotation.SuppressLint
import android.content.Context
import androidx.work.WorkerParameters
import org.jsoup.Jsoup
import rasel.lunar.launcher.model.TheQoo
import rasel.lunar.launcher.model.getHref
import rasel.lunar.launcher.model.getRssData
import rasel.lunar.launcher.model.getT
import rasel.lunar.launcher.utils.BLog

class TheQooGetter : BaseGetter {
    companion object {
        val TAG = "TheQooGetter"
    }
    constructor(context: Context, workerParams: WorkerParameters) : super(context, workerParams) {
    }

    fun parseTQoo(tq_tr : org.jsoup.nodes.Element) {
//        BLog.LOGE("tq_tr >>>> ${tq_tr}")
        var desc = tq_tr.getElementsByClass("cate").getT()
        var title = tq_tr.getElementsByClass("title").getT()
        var pageLink = tq_tr.getElementsByTag("a").getHref()
        var dateTime = tq_tr.getElementsByClass("time").getT()

//        BLog.LOGE("${TAG} :::: desc >>> $desc")
//        BLog.LOGE("${TAG} :::: title >>> $title")
//        BLog.LOGE("${TAG} :::: pageLink >>> $pageLink")
//        BLog.LOGE("${TAG} :::: dateTime >>> $dateTime")

        if (title.length > 0 && pageLink.length > 0) {
            TheQoo().let { tq ->
                tq.title = title
                tq.link = "https://theqoo.net".plus(pageLink)
                tq.dateTiem = dateTime
                tq.desc = desc
                if (tq.pubDate() > limitDateTime) {
                    temp.add(tq.getRssData())
                }
            }
        }


    }

    @SuppressLint("RestrictedApi")
    override fun realWork(): Result {

        try {
            val testUrl2 = arrayListOf("https://theqoo.net/hot")
            testUrl2.forEach { url ->
                Jsoup.connect(url)
                    .userAgent(USAGT)
                    .get().let { ruli ->
                        BLog.LOGE("test ${testUrl2} >> ${ruli.title()}")
                        ruli.getElementsByTag("tr").forEach { ruli_tr ->
                            parseTQoo(ruli_tr)
                        }
                    }
            }
        } catch (e:Exception){e.printStackTrace()}
        return  Result.success().apply {
//            BLog.LOGE("theqoo temp >>>> ${temp.size}")
            WorkersDb.insertBulkData(temp)
        }
    }
}