package bou.amine.apps.readerforselfossv2.utils

import bou.amine.apps.readerforselfossv2.dao.ITEM
import bou.amine.apps.readerforselfossv2.dao.SOURCE
import bou.amine.apps.readerforselfossv2.dao.TAG
import bou.amine.apps.readerforselfossv2.model.SelfossModel

fun TAG.toView(): SelfossModel.Tag =
    SelfossModel.Tag(
        this.name,
        this.color,
        this.unread.toInt(),
    )

fun SOURCE.toView(): SelfossModel.SourceDetail =
    SelfossModel.SourceDetail(
        this.id.toInt(),
        this.title,
        null,
        this.tags?.split(","),
        this.spout,
        this.error,
        this.icon,
        if (this.url != null) SelfossModel.SourceParams(this.url) else null,
    )

fun SelfossModel.SourceDetail.toEntity(): SOURCE =
    SOURCE(
        this.id.toString(),
        this.title.getHtmlDecoded(),
        this.tags?.joinToString(",").orEmpty(),
        this.spout.orEmpty(),
        this.error.orEmpty(),
        this.icon.orEmpty(),
        this.params?.url,
    )

fun SelfossModel.Tag.toEntity(): TAG =
    TAG(
        this.tag,
        this.color,
        this.unread.toLong(),
    )

fun ITEM.toView(): SelfossModel.Item =
    SelfossModel.Item(
        this.id.toInt(),
        this.datetime,
        this.title,
        this.content,
        this.unread,
        this.starred,
        this.thumbnail,
        this.icon,
        this.link,
        this.sourcetitle,
        this.tags.split(","),
        this.author,
    )

fun SelfossModel.Item.toEntity(): ITEM =
    ITEM(
        this.id.toString(),
        this.datetime,
        this.title.getHtmlDecoded(),
        this.content,
        this.unread,
        this.starred,
        this.thumbnail,
        this.icon,
        this.link,
        this.sourcetitle.getHtmlDecoded(),
        this.tags.joinToString(","),
        this.author,
    )

fun SelfossModel.Tag.getColorHexCode(): String =
    if (this.color.length == 4) { // #000
        val char1 = this.color.get(1)
        val char2 = this.color.get(2)
        val char3 = this.color.get(3)
        "#$char1$char1$char2$char2$char3$char3"
    } else {
        this.color
    }