package rasel.lunar.launcher.model

import io.realm.kotlin.types.RealmObject
import io.realm.kotlin.types.annotations.Ignore
import io.realm.kotlin.types.annotations.PrimaryKey
import org.jsoup.select.Elements
import rasel.lunar.launcher.utils.JamoUtils
import rasel.lunar.launcher.utils.afterDay
import rasel.lunar.launcher.utils.beforeDay
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.TimeZone


fun Elements.getT()  = if (size > 0) get(0).text() else ""
fun Elements.getHref()  = if (size > 0) get(0).attr("href") else ""
val dateFormat = SimpleDateFormat("hh:mm / yy - MM - dd")
class Clien : DcInside() {
    companion object{
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    }
    override fun category(): RssDataType {
        return RssDataType.Clien
    }


    override fun pubDate(): Long {
        if (dateTiemL < 1L) {
            if (dateTiem?.length ?: 0 < 1) return 0L
            return  dateFormat.parse(dateTiem!!).time.apply {
                dateTiemL = this
            }
        } else {
            return dateTiemL
        }
    }

}
class Arca : RssDataInterface {
    var link : String? = null
    var title : String? = null
    var thumbnail : String? = null
    var desc : String? = null
    var dateTiem : String? = null
    var updateDateTime : Long = 0L
    override fun title(): String {
        return title ?: ""
    }

    override fun thumbnailUrl(): String {
        return thumbnail ?: ""
    }

    override fun originPage(): String {
        return link ?: ""
    }

    override fun description(): String {
        return  desc ?: ""
    }

    override fun pubDate(): Long {
        var date = Date()
        var dateTime = date.time
        var before = 0
        if (updateDateTime == 0L) {
            try {
//                BLog.LOGE("this.dateTiem >>> ${this.dateTiem}")
                val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                sdf.timeZone = TimeZone.getTimeZone("GMT")
                updateDateTime = sdf.parse(this.dateTiem!!).time
//                BLog.LOGE("updateDateTime >>>> ${dateFormat.format(Date(updateDateTime))}" )
//                var targetDate = this.dateTiem ?: ""
//                if (targetDate?.length ?: 0 > 1) {
//                    var dateDesc = targetDate
//                    var isBefore = dateDesc.contains("전")
//                    val dayString = dateDesc.replace("[^0-9]".toRegex(), "")
//                    before = dayString.toInt()
//                    if (dateDesc.contains("년")) {
//                        before = 365 * before
//                        dateTime = if (isBefore) beforeDay(date, before) else afterDay(date, before)
//                    } else if (dateDesc.contains("월")) {
//                        before = 30 * before
//                        dateTime = if (isBefore) beforeDay(date, before) else afterDay(date, before)
//                    } else if (dateDesc.contains("주")) {
//                        before = 7 * before
//                        dateTime = if (isBefore) beforeDay(date, before) else afterDay(date, before)
//                    } else if (dateDesc.contains("일")) {
//                        dateTime = if (isBefore) beforeDay(date, before) else afterDay(date, before)
//                    } else if (dateDesc.contains("시간")) {
//                        dateTime =
//                            if (isBefore) dateTime.minus(before.times(1000L * 60L * 60L)) else dateTime.plus(
//                                before.times(1000L * 60L * 60L)
//                            )
//                    } else if (dateDesc.contains("분")) {
//                        dateTime =
//                            if (isBefore) dateTime.minus(before.times(1000L * 60L)) else dateTime.plus(
//                                before.times(1000L * 60L)
//                            )
//                    }
//                    else if (dateDesc.contains("초")) {
//                        dateTime =
//                            if (isBefore) dateTime.minus(before.times(1000L)) else dateTime.plus(
//                                before.times(1000L)
//                            )
//                    }
//                }

            } catch (e: Exception) {

            } finally {
//                updateDateTime = dateTime
            }
        } else {
            dateTime = updateDateTime
        }
        return dateTime
    }

    override fun category(): RssDataType {
        return RssDataType.Arca
    }
    override fun getCho(): String? {
        return JamoUtils.split(title!!).joinToString("")
    }
}







open class DcInside : RssDataInterface {
    var link : String? = null
    var title : String? = null
    var thumbnail : String? = null
    var desc : String? = null
    var dateTiem : String? = null

    var dateTiemL : Long = 0L

    val dateF = SimpleDateFormat("MM-dd")
    val timeF = SimpleDateFormat("HH:mm")
    override fun title(): String {
        return title ?:""
    }

    override fun thumbnailUrl(): String {
        return thumbnail ?: ""
    }

    override fun originPage(): String {
        return link ?:""
    }

    override fun description(): String {
        return desc ?: ""
    }

    override fun pubDate(): Long {
        if (dateTiemL < 1L) {
            if (dateTiem?.length ?: 0 < 1) return 0L
            return if (dateTiem?.contains(":") == true) {
                val cal: Calendar = Calendar.getInstance()
                cal.setTime(Date())
                cal.set(Calendar.HOUR_OF_DAY, dateTiem!!.split(":")[0].toInt())
                cal.set(Calendar.MINUTE, dateTiem!!.split(":")[1].toInt())
//                cal.set(Calendar.MINUTE, dateTiem!!.split(":")[1].toI nt())
                dateTiemL =   cal.timeInMillis
                dateTiemL
            } else if (dateTiem?.contains("-") == true) {
                val cal: Calendar = Calendar.getInstance()
                cal.setTime(Date())
                cal.set(Calendar.MONTH, dateTiem!!.split("-")[0].toInt() - 1)
                cal.set(Calendar.DAY_OF_MONTH, dateTiem!!.split("-")[1].toInt())
//                cal.add(Calendar.DAY_OF_MONTH, -1)
                dateTiemL = cal.timeInMillis
                dateTiemL
            } else {
                0L
            }
        } else {
            return dateTiemL
        }
    }

    override fun category(): RssDataType {
        return RssDataType.DcInside
    }

    override fun getCho(): String? {
        return JamoUtils.split(title!!).joinToString("")
    }
}


class RuliWeb : DcInside() {
    override fun category(): RssDataType {
        return RssDataType.RuliWeb
    }
}
class TheQoo : DcInside() {
    override fun category(): RssDataType {
        return RssDataType.TheQoo
    }
}


class RssData : RealmObject, RssDataInterface {

    @PrimaryKey
    var originPage : String? = null
    var title : String? = null
    var description : String? = null
    var thumbnail : String? = null
    var pubDate : Long = 0L
    var category : String? = null

    var chosung : String? = null

    @Ignore
    var mRssDataType : RssDataType? = null
    override fun title(): String {
        return  when(category()){
            RssDataType.NewsFeed -> {
                if(title?.length ?: 0 > 30) title?.substring(0,30).plus("...") else title ?: ""
            }
            else -> title ?: ""
        }.apply {
            chosung = JamoUtils.split(this).joinToString("")
        }
    }

    override fun thumbnailUrl(): String {
        return thumbnail ?: ""
    }

    override fun originPage(): String {
        return originPage ?: ""
    }

    override fun description(): String {

        return  when(category()){
            RssDataType.YOUTUBE -> {
                if(description?.contains("게시자") == true) description!!.split("게시자")[0] else description ?: ""
            }
            RssDataType.NewsFeed -> {
                category().name
            }
            else ->  description.plus(" / ").plus(category().name)
        }
    }

    override fun pubDate(): Long {
        return pubDate
    }

    override fun category(): RssDataType {
        if (mRssDataType == null)
            mRssDataType = RssDataType.valueOf(category!!)
        return mRssDataType!!
    }

    override fun getCho(): String? {
        return chosung
    }
}


open class Dotax(var pageLink : String,
                 var desc : String,
                 var dateTime : String,
                 var title : String,
                 var thumbnail : String) : RssDataInterface {
    var updateDateTime = 0L
    override fun title(): String {
        return title
    }

    override fun thumbnailUrl(): String {
        return thumbnail
    }

    override fun originPage(): String {
        return "https://m.cafe.daum.net".plus(pageLink)
    }

    override fun description(): String {
        return desc
    }
    override fun pubDate(): Long {
        var date = Date()
        var dateTime = date.time
        var before = 0
        if (updateDateTime == 0L) {
            try {
                var targetDate = this.dateTime ?: ""
                if (targetDate?.length ?: 0 > 1) {
                    var dateDesc = targetDate
                    var isBefore = dateDesc.contains("전")
                    val dayString = dateDesc.replace("[^0-9]".toRegex(), "")
                    before = dayString.toInt()
                    if (dateDesc.contains("년")) {
                        before = 365 * before
                        dateTime = if (isBefore) beforeDay(date, before) else afterDay(date, before)
                    } else if (dateDesc.contains("월")) {
                        before = 30 * before
                        dateTime = if (isBefore) beforeDay(date, before) else afterDay(date, before)
                    } else if (dateDesc.contains("주")) {
                        before = 7 * before
                        dateTime = if (isBefore) beforeDay(date, before) else afterDay(date, before)
                    } else if (dateDesc.contains("일")) {
                        dateTime = if (isBefore) beforeDay(date, before) else afterDay(date, before)
                    } else if (dateDesc.contains("시간")) {
                        dateTime =
                            if (isBefore) dateTime.minus(before.times(1000L * 60L * 60L)) else dateTime.plus(
                                before.times(1000L * 60L * 60L)
                            )
                    } else if (dateDesc.contains("분")) {
                        dateTime =
                            if (isBefore) dateTime.minus(before.times(1000L * 60L)) else dateTime.plus(
                                before.times(1000L * 60L)
                            )
                    }
                    else if (dateDesc.contains("초")) {
                        dateTime =
                            if (isBefore) dateTime.minus(before.times(1000L)) else dateTime.plus(
                                before.times(1000L)
                            )
                    }
                }

            } catch (e: Exception) {

            } finally {
                updateDateTime = dateTime
            }
        } else {
            dateTime = updateDateTime
        }
        return dateTime
    }
    override fun category(): RssDataType {
        return RssDataType.Dotax
    }
    override fun getCho(): String? {
        return JamoUtils.split(title!!).joinToString("")
    }
}

data class FmKorea(var apageLink : String,
                   var adesc : String,
                   var adateTime : String,
                   var atitle : String,
                   var athumbnail : String) : Dotax(apageLink, adesc, adateTime, atitle, athumbnail) {
    override fun originPage(): String {
        return pageLink
    }
    override fun category(): RssDataType {
        return RssDataType.FmKorae
    }
}

fun RssDataInterface.getRssData() : RssData {
    return RssData().apply {
        title = this@getRssData.title()
        description = this@getRssData.description()
        originPage = this@getRssData.originPage()
        thumbnail = this@getRssData.thumbnailUrl()
        pubDate = this@getRssData.pubDate()
        chosung = this@getRssData.getCho()
        category = this@getRssData.category().name
    }
}