package eu.friedcutlet.yokan.ui.screens.browse import eu.friedcutlet.yokan.services.extensions.FilterSelection import eu.friedcutlet.yokan.services.extensions.SourceFilter import eu.friedcutlet.yokan.services.extensions.SourceFilterKind data class GenreSearchRequest(val query: String, val selections: Map) /** Use the extension's outbound filter values, never the displayed genre label as a value. */ fun genreSearchRequest(genre: String, filters: List): GenreSearchRequest { val tag = genre.trim() val candidates = filters.mapNotNull { filter -> // Some extensions expose the same labels in include and exclude groups. if (filter.id.contains("exclude", ignoreCase = true) || excludedGroup.containsMatchIn(filter.name)) return@mapNotNull null val name = filter.name.substringAfterLast(':').substringAfterLast('/').trim() val entry = filter.entries.firstOrNull { it.label.trim().equals(tag, ignoreCase = true) } val selection = when (filter.kind) { SourceFilterKind.MultiSelect -> entry?.let { FilterSelection.Multi(setOf(it.value)) } SourceFilterKind.SingleSelect -> entry?.let { FilterSelection.Single(it.value) } SourceFilterKind.Toggle -> if (name.equals(tag, ignoreCase = true)) FilterSelection.Toggle(true) else null SourceFilterKind.TriState -> if (name.equals(tag, ignoreCase = true)) FilterSelection.TriState(1) else null SourceFilterKind.Text, SourceFilterKind.Sort -> null } selection?.let { filter to it } } val candidate = candidates.firstOrNull { (filter, _) -> filter.name.contains("genre", ignoreCase = true) || filter.name.contains("tag", ignoreCase = true) } ?: candidates.firstOrNull() val selections = candidate?.let { (filter, selection) -> mapOf(filter.id to selection) }.orEmpty() return GenreSearchRequest(query = if (selections.isEmpty()) tag else "", selections = selections) } private val excludedGroup = Regex("\\b(exclude|excluded|excluding|without)\\b", RegexOption.IGNORE_CASE)