package com.pixelized.biblib.utils.extention

import androidx.annotation.StringDef
import com.pixelized.biblib.model.book.Book
import com.pixelized.biblib.model.book.Series
import com.pixelized.biblib.network.client.IBibLibClient
import com.pixelized.biblib.ui.screen.home.common.item.BookThumbnailUio
import com.pixelized.biblib.ui.screen.home.detail.BookDetailUio


@Retention(AnnotationRetention.SOURCE)
@StringDef(
    IBibLibClient.THUMBNAIL_URL,
    IBibLibClient.COVER_URL,
)
annotation class CoverUrl

fun Book.toThumbnailUio(
    @CoverUrl coverBaseUrl: String = IBibLibClient.COVER_URL,
    @CoverUrl thumbnailBaseUrl: String = IBibLibClient.THUMBNAIL_URL
) = BookThumbnailUio(
    id = id,
    title = title,
    series = series?.let { toLabel(it) } ?: "",
    genre = genre?.joinToString { it.name } ?: "",
    author = author.joinToString { it.name },
    language = language?.displayLanguage?.capitalize() ?: "",
    date = releaseDate.year(),
    isNew = isNew,
    thumbnail = "${thumbnailBaseUrl}/$id.jpg",
    cover = "${coverBaseUrl}/$id.jpg",
)

fun Book.toDetailUio(
    @CoverUrl coverBaseUrl: String = IBibLibClient.COVER_URL,
    placeHolder: Boolean,
) = BookDetailUio(
    id = id,
    title = title,
    authorId = author.firstOrNull()?.id,
    authors = author.map { BookDetailUio.AuthorUio(id = it.id, it.name) },
    rating = rating?.toFloat() ?: 0.0f,
    language = language?.displayLanguage?.capitalize() ?: "",
    date = releaseDate.shortDate(),
    seriesId = series?.id,
    series = series?.let {
        BookDetailUio.SeriesUio(
            id = it.id,
            name = it.name,
            label = toLabel(series)
        )
    },
    description = synopsis ?: "",
    cover = "${coverBaseUrl}/$id.jpg",
    placeHolder = placeHolder,
)

fun Book.toLabel(series: Series): String {
    return when {
        seriesIndex != null -> "${series.name} - $seriesIndex"
        else -> series.name
    }
}