package eu.friedcutlet.yokan.data import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbDisplayType import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbReaderMode import eu.friedcutlet.yokan.database.DbRepo import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbSourceCodeLanguage import eu.friedcutlet.yokan.database.DbStatus import eu.friedcutlet.yokan.database.DbTitleMetadata import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.domain.Category import eu.friedcutlet.yokan.domain.DisplayType import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.History import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.domain.ReaderMode import eu.friedcutlet.yokan.domain.Repo import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.domain.SourceCodeLanguage import eu.friedcutlet.yokan.domain.Status import eu.friedcutlet.yokan.domain.Track import eu.friedcutlet.yokan.domain.TrackStatus import eu.friedcutlet.yokan.domain.UpdateEntry import eu.friedcutlet.yokan.domain.UserSettings // Database ↔ domain model conversions; reuse these instead of adding local copies. internal fun DbCategory.toDomain(): Category = Category( id = id, name = name, forItemType = forItemType.toDomain(), position = position ?: 0, hidden = hidden ?: false, shouldUpdate = shouldUpdate ?: true, ) internal fun DbManga.toDomain(settings: DbSettings): Manga = toDomain(settings.titleMetadataFor(id)) /** One metadata index per list mapping; preserve the first match used by single-title reads. */ internal fun Iterable.toDomainMangas(settings: DbSettings): List { val metadata = HashMap() settings.titleMetadata.orEmpty().forEach { metadata.getOrPut(it.mangaId) { it } } return map { it.toDomain(metadata[it.id]) } } private fun DbManga.toDomain(metadata: DbTitleMetadata?): Manga { val titles = mergedDistinct(listOf(name.orEmpty()) + metadata?.titles.orEmpty()) return Manga( id = id, name = name.orEmpty(), alternativeTitles = titles, link = link.orEmpty(), imageUrl = imageUrl, customCoverImage = customCoverImage, customCoverFromTracker = customCoverFromTracker, description = description.orEmpty(), privateNote = privateNote, nextEpisodeAiringAt = nextEpisodeAiringAt, nextEpisodeNumber = nextEpisodeNumber, cast = cast, parentId = parentId, fetchesSeasons = fetchType == eu.friedcutlet.yokan.database.DbFetchType.Seasons, seasonNumber = seasonNumber, author = author, artist = artist, status = status.toDomain(), itemType = itemType.toDomain(), genres = genre.orEmpty(), favorite = favorite, source = source.orEmpty(), lang = lang.orEmpty(), dateAddedMillis = dateAdded ?: 0, lastUpdateMillis = lastUpdate ?: 0, lastReadMillis = lastRead, categories = categories.orEmpty(), isLocalArchive = isLocalArchive, smartUpdateDays = smartUpdateDays, sourceId = sourceId, metadataServerId = metadata?.metadataServerId, metadataSource = metadata?.metadataSource, metadataUpdatedAt = metadata?.updatedAt ?: 0L, ) } internal fun DbSettings.titleMetadataFor(mangaId: Long): DbTitleMetadata? = titleMetadata.orEmpty().firstOrNull { it.mangaId == mangaId } internal fun mergedDistinct(values: List): List = values.mapNotNull { value -> value.trim().takeIf { it.isNotBlank() } } .distinctBy { it.lowercase() } internal fun ItemType.toDb(): DbItemType = when (this) { ItemType.Manga -> DbItemType.Manga ItemType.Anime -> DbItemType.Anime ItemType.Novel -> DbItemType.Novel } internal fun DbItemType.toDomain(): ItemType = when (this) { DbItemType.Manga -> ItemType.Manga DbItemType.Anime -> ItemType.Anime DbItemType.Novel -> ItemType.Novel } internal fun DbStatus.toDomain(): Status = when (this) { DbStatus.Ongoing -> Status.Ongoing DbStatus.Completed -> Status.Completed DbStatus.Canceled -> Status.Canceled DbStatus.Unknown -> Status.Unknown DbStatus.OnHiatus -> Status.OnHiatus DbStatus.PublishingFinished -> Status.PublishingFinished DbStatus.Licensed -> Status.Licensed DbStatus.Upcoming -> Status.Upcoming } internal fun DbSourceCodeLanguage.toDomain(): SourceCodeLanguage = when (this) { DbSourceCodeLanguage.JavaScript -> SourceCodeLanguage.JavaScript DbSourceCodeLanguage.Mihon -> SourceCodeLanguage.Mihon DbSourceCodeLanguage.LnReader -> SourceCodeLanguage.LnReader DbSourceCodeLanguage.Aidoku -> SourceCodeLanguage.Aidoku } internal fun DbSettings.toDomain(): UserSettings = UserSettings( displayType = displayType.toDomain(), followSystemTheme = followSystemTheme, darkTheme = themeIsDark, incognitoMode = incognitoMode, downloadedOnly = downloadedOnlyMode, defaultReaderMode = defaultReaderMode.toDomain(), libraryShowCategoryTabs = libraryShowCategoryTabs, libraryShowLanguage = libraryShowLanguage, libraryShowSource = libraryShowSource, libraryShowNumbersOfItems = libraryShowNumbersOfItems, showPagesNumber = showPagesNumber, concurrentDownloads = concurrentDownloads, allowConcurrentDownloads = allowConcurrentDownloads, downloadDelaySeconds = downloadDelaySeconds, checkForAppUpdates = checkForAppUpdates, checkForExtensionUpdates = checkForExtensionUpdates, ) internal fun DbSettings.withUserSettings(settings: UserSettings): DbSettings = copy( displayType = settings.displayType.toDb(), followSystemTheme = settings.followSystemTheme, themeIsDark = settings.darkTheme, incognitoMode = settings.incognitoMode, downloadedOnlyMode = settings.downloadedOnly, defaultReaderMode = settings.defaultReaderMode.toDb(), libraryShowCategoryTabs = settings.libraryShowCategoryTabs, libraryShowLanguage = settings.libraryShowLanguage, libraryShowSource = settings.libraryShowSource, libraryShowNumbersOfItems = settings.libraryShowNumbersOfItems, showPagesNumber = settings.showPagesNumber, concurrentDownloads = settings.concurrentDownloads, allowConcurrentDownloads = settings.allowConcurrentDownloads, downloadDelaySeconds = settings.downloadDelaySeconds, checkForAppUpdates = settings.checkForAppUpdates, checkForExtensionUpdates = settings.checkForExtensionUpdates, ) internal fun DbDisplayType.toDomain(): DisplayType = when (this) { DbDisplayType.CompactGrid -> DisplayType.CompactGrid DbDisplayType.ComfortableGrid -> DisplayType.ComfortableGrid DbDisplayType.CoverOnlyGrid -> DisplayType.CoverOnlyGrid DbDisplayType.List -> DisplayType.List } internal fun DisplayType.toDb(): DbDisplayType = when (this) { DisplayType.CompactGrid -> DbDisplayType.CompactGrid DisplayType.ComfortableGrid -> DbDisplayType.ComfortableGrid DisplayType.CoverOnlyGrid -> DbDisplayType.CoverOnlyGrid DisplayType.List -> DbDisplayType.List } internal fun DbReaderMode.toDomain(): ReaderMode = when (this) { DbReaderMode.Vertical, DbReaderMode.VerticalContinuous -> ReaderMode.ContinuousVertical DbReaderMode.Webtoon -> ReaderMode.Webtoon DbReaderMode.Ltr, DbReaderMode.Rtl, DbReaderMode.HorizontalContinuous, DbReaderMode.HorizontalContinuousRtl -> ReaderMode.Paged } internal fun ReaderMode.toDb(): DbReaderMode = when (this) { ReaderMode.Paged -> DbReaderMode.Ltr ReaderMode.ContinuousVertical -> DbReaderMode.VerticalContinuous ReaderMode.Webtoon -> DbReaderMode.Webtoon ReaderMode.Novel -> DbReaderMode.Vertical } internal fun DbTrackStatus.toDomain(): TrackStatus = when (this) { DbTrackStatus.Reading -> TrackStatus.Reading DbTrackStatus.Completed -> TrackStatus.Completed DbTrackStatus.OnHold -> TrackStatus.OnHold DbTrackStatus.Dropped -> TrackStatus.Dropped DbTrackStatus.PlanToRead -> TrackStatus.PlanToRead DbTrackStatus.ReReading -> TrackStatus.ReReading DbTrackStatus.Watching -> TrackStatus.Watching DbTrackStatus.PlanToWatch -> TrackStatus.PlanToWatch DbTrackStatus.ReWatching -> TrackStatus.ReWatching } internal fun DbSource.toDomain(): Source = Source( id = id, name = name, baseUrl = baseUrl, lang = lang, itemType = itemType.toDomain(), typeSource = typeSource, iconUrl = iconUrl, isActive = isActive, isAdded = isAdded, isPinned = isPinned, isNsfw = isNsfw, hasCloudflare = hasCloudflare, supportLatest = supportLatest == true, version = version, versionLast = versionLast, lastUsed = lastUsed, isObsolete = isObsolete, sourceCodeLanguage = sourceCodeLanguage.toDomain(), repo = repo?.toDomain(), notes = notes, ) internal fun DbRepo.toDomain(): Repo = Repo( name = name.orEmpty(), jsonUrl = jsonUrl.orEmpty(), website = website, ) /** `null` when the row lost its title or chapter link. */ internal fun DbHistory.toDomain(manga: DbManga?, chapter: DbChapter?): History? = History( id = id, mangaId = mangaId ?: return null, chapterId = chapterId ?: return null, itemType = itemType.toDomain(), title = manga?.name.orEmpty(), chapterName = chapter?.name.orEmpty(), date = date.orEmpty(), readingTimeSeconds = readingTimeSeconds ?: 0, updatedAt = updatedAt, lastPageRead = chapter?.lastPageRead.orEmpty(), chapterIsRead = chapter?.isRead ?: false, ) /** `null` when the row lost its title link. */ internal fun DbUpdate.toDomain(manga: DbManga?, chapter: DbChapter?): UpdateEntry? = UpdateEntry( id = id, mangaId = mangaId ?: return null, chapterId = chapterId ?: 0L, itemType = manga?.itemType?.toDomain() ?: ItemType.Manga, title = manga?.name.orEmpty(), chapterName = chapterName.orEmpty(), source = manga?.source.orEmpty(), date = date.orEmpty(), isRead = chapter?.isRead ?: false, updatedAt = updatedAt, ) internal fun DbTrack.toDomain(): Track = Track( id = id, libraryId = libraryId ?: 0, mediaId = mediaId ?: 0, mangaId = mangaId ?: 0, syncId = syncId ?: 0, title = title.orEmpty(), progress = lastChapterRead ?: 0, total = totalChapter ?: 0, score = score ?: 0, status = status.toDomain(), trackingUrl = trackingUrl.orEmpty(), itemType = itemType.toDomain(), ) internal fun toDomainChapter(it: DbChapter) = eu.friedcutlet.yokan.domain.Chapter( id = it.id, mangaId = it.mangaId ?: 0, name = it.name.orEmpty(), url = it.url, dateUpload = it.dateUpload, scanlator = it.scanlator, isBookmarked = it.isBookmarked, isRead = it.isRead, lastPageRead = it.lastPageRead, archivePath = it.archivePath, isFiller = it.fillerOverride ?: it.isFiller, thumbnailUrl = it.thumbnailUrl, description = it.description, downloadSize = it.downloadSize, duration = it.duration, fetchedAt = it.fetchedAt, number = it.number, season = it.season, numberingName = it.numberingName, fillerOverride = it.fillerOverride, )