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.Dotax
import rasel.lunar.launcher.model.getRssData

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

    }

    @SuppressLint("RestrictedApi")
    override fun realWork(): Result {
        try {
            val dotaxUrls = arrayListOf("https://m.cafe.daum.net/dotax",
                "https://m.cafe.daum.net/dotax/_rec?page=2",
                "https://m.cafe.daum.net/dotax/_rec?page=3"
            )
            dotaxUrls?.forEach {
                Jsoup.connect(it).userAgent(USAGT).get()?.let { dotax ->
                    dotax.getElementsByTag("li").forEach { dotax_li ->
                        if (dotax_li.getElementsByTag("a").size > 0 && dotax_li.getElementsByClass("board_name")
                                .html().contains("웃긴")
                        ) {
                            val pageLink = dotax_li.getElementsByTag("a").get(0).attr("href")
                            val desc = dotax_li.getElementsByClass("board_name").text()
                            val dateTime = dotax_li.getElementsByClass("created_at").text()
                            val title = dotax_li.getElementsByClass("txt_detail").text()
                            val thumbnail = dotax_li.getElementsByClass("article_thumb").text()
                            if (pageLink.length > 0 && desc.length > 0 && dateTime.length > 0 && title.length > 0) {
                                Dotax(pageLink, desc, dateTime, title, thumbnail).let { dotax ->
                                    if(dotax.pubDate() > commicsDateTime) {
                                        temp.add(dotax.getRssData())
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (e : Exception) {e.printStackTrace()}
        return  Result.success().apply {
            WorkersDb.insertBulkData(temp)
        }
    }
}