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.FmKorea
import rasel.lunar.launcher.model.getRssData
import java.util.Date

class FmKoreaGetter : BaseGetter {
    constructor(context: Context, workerParams: WorkerParameters) : super(context, workerParams) {

    }

    @SuppressLint("RestrictedApi")
    override fun realWork(): Result {
        val now = Date()
        try {
            val fmkoreaUrls = arrayListOf("https://www.fmkorea.com")
            fmkoreaUrls.forEach { Jsoup.connect(it).userAgent(USAGT).get().let { fmkorea ->
//            BLog.LOGE("fmkorea >>> ${fmkorea.title()}")
                fmkorea.getElementsByTag("li").forEach { fmkorea_li ->
                    if (fmkorea_li.getElementsByClass("title").text().length > 0 && fmkorea_li.getElementsByTag("a").size > 0 &&fmkorea_li.getElementsByTag("a").get(0).attr("href").length > 0) {
//                    BLog.LOGE("fmkorea_li >>> ${fmkorea_li}")
                        val title = fmkorea_li.getElementsByClass("title").text()
                        val tumb = "https://".plus(
                            fmkorea_li.getElementsByClass("thumb").attr("data-original")
                        )
                        val pageUrl = "https://www.fmkorea.com".plus(
                            fmkorea_li.getElementsByTag("a").get(0).attr("href")
                        )
                        val desc = fmkorea_li.getElementsByClass("category").text()
                        val date = fmkorea_li.getElementsByClass("regdate").text()
                        FmKorea(pageUrl, desc, date, title, tumb).apply {
                            if(desc?.contains("유머")  == true|| desc?.contains("음악") == true|| desc?.contains("영화")== true ||
                                desc?.contains("TV")== true || desc?.contains("미스터리")== true || desc?.contains("역사")== true) {
                                if (this.pubDate() > commicsDateTime) {
                                    temp.add(this.getRssData())
                                }
                            }
                        }

                    }
                }
            } }
        } catch (e : Exception) {e.printStackTrace()}

        return  Result.success().apply {
            WorkersDb.insertBulkData(temp)
        }
    }
}