From a0eea05f8f794e32abc7c85a390302565ca79601 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 21:40:41 +0100 Subject: [PATCH] chore: initial import --- .gitignore | 15 + README.md | 167 ++++++ app/build.gradle.kts | 85 +++ app/proguard-rules.pro | 1 + app/src/main/AndroidManifest.xml | 26 + .../sportssuitability/MainActivity.kt | 164 ++++++ .../sportssuitability/SportsSuitabilityApp.kt | 27 + .../alerts/AlertScheduler.kt | 119 ++++ .../alerts/DailyAlertWorker.kt | 87 +++ .../alerts/NotificationHelper.kt | 79 +++ .../alerts/WeeklyForecastWorker.kt | 106 ++++ .../data/local/AppDatabase.kt | 62 ++ .../sportssuitability/data/local/Spot.kt | 32 ++ .../sportssuitability/data/local/SpotDao.kt | 34 ++ .../data/prefs/AppSettings.kt | 97 ++++ .../data/prefs/SettingsRepository.kt | 145 +++++ .../sportssuitability/data/prefs/Tunables.kt | 300 ++++++++++ .../sportssuitability/data/prefs/Units.kt | 117 ++++ .../data/remote/NetworkModule.kt | 44 ++ .../data/remote/OpenMeteoApi.kt | 82 +++ .../data/remote/OpenMeteoModels.kt | 157 +++++ .../data/repository/Conditions.kt | 141 +++++ .../data/repository/SpotsRepository.kt | 314 ++++++++++ .../data/repository/Suitability.kt | 531 +++++++++++++++++ .../data/repository/WeatherCode.kt | 49 ++ .../zenvairo/sportssuitability/ui/Metrics.kt | 220 +++++++ .../sportssuitability/ui/SportUiInfo.kt | 16 + .../sportssuitability/ui/SpotsViewModel.kt | 188 ++++++ .../ui/SpotsViewModelFactory.kt | 18 + .../sportssuitability/ui/SuitabilityUi.kt | 15 + .../ui/components/AddSpotDialog.kt | 75 +++ .../sportssuitability/ui/components/Common.kt | 135 +++++ .../ui/components/ConditionsCard.kt | 369 ++++++++++++ .../ui/components/DayDetailDialog.kt | 182 ++++++ .../ui/components/SpotSettingsDialog.kt | 111 ++++ .../ui/screens/SettingsScreen.kt | 544 ++++++++++++++++++ .../ui/screens/SportScreen.kt | 150 +++++ .../sportssuitability/ui/theme/Theme.kt | 33 ++ .../res/drawable/ic_launcher_background.xml | 8 + .../res/drawable/ic_launcher_foreground.xml | 14 + .../res/mipmap-anydpi-v26/ic_launcher.xml | 5 + .../mipmap-anydpi-v26/ic_launcher_round.xml | 5 + app/src/main/res/values/strings.xml | 4 + app/src/main/res/values/themes.xml | 4 + .../alerts/AlertSchedulerTest.kt | 68 +++ .../data/repository/SuitabilityTest.kt | 307 ++++++++++ build.gradle.kts | 7 + gradle.properties | 6 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 47505 bytes gradle/wrapper/gradle-wrapper.properties | 9 + gradlew | 248 ++++++++ gradlew.bat | 82 +++ settings.gradle.kts | 17 + 53 files changed, 5821 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 app/build.gradle.kts create mode 100644 app/proguard-rules.pro create mode 100644 app/src/main/AndroidManifest.xml create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/MainActivity.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/SportsSuitabilityApp.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/alerts/AlertScheduler.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/alerts/DailyAlertWorker.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/alerts/NotificationHelper.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/alerts/WeeklyForecastWorker.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/local/AppDatabase.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/local/Spot.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/local/SpotDao.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/prefs/AppSettings.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/prefs/SettingsRepository.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Tunables.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Units.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/remote/NetworkModule.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/remote/OpenMeteoApi.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/remote/OpenMeteoModels.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/repository/Conditions.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/repository/SpotsRepository.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/repository/Suitability.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/data/repository/WeatherCode.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/Metrics.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/SportUiInfo.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/SpotsViewModel.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/SpotsViewModelFactory.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/SuitabilityUi.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/components/AddSpotDialog.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/components/Common.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/components/ConditionsCard.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/components/DayDetailDialog.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/components/SpotSettingsDialog.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SettingsScreen.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SportScreen.kt create mode 100644 app/src/main/java/com/zenvairo/sportssuitability/ui/theme/Theme.kt create mode 100644 app/src/main/res/drawable/ic_launcher_background.xml create mode 100644 app/src/main/res/drawable/ic_launcher_foreground.xml create mode 100644 app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 app/src/main/res/values/strings.xml create mode 100644 app/src/main/res/values/themes.xml create mode 100644 app/src/test/java/com/zenvairo/sportssuitability/alerts/AlertSchedulerTest.kt create mode 100644 app/src/test/java/com/zenvairo/sportssuitability/data/repository/SuitabilityTest.kt create mode 100644 build.gradle.kts create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle.kts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b05138 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +.gradle/ +.kotlin/ +build/ +local.properties +*.apk +*.aab +*.jks +*.keystore +.idea/ +*.iml +.DS_Store +captures/ +.externalNativeBuild/ +.cxx/ +.claude/settings.local.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..d36b46a --- /dev/null +++ b/README.md @@ -0,0 +1,167 @@ +# SportsSuitability + +Android app (Kotlin + Jetpack Compose) that answers one question for every place you save: +**can I go today?** — for **surf**, **windsurf** and **skiing**. + +It does three things: + +1. Shows every forecast reading that matters for the sport, now and for the next 7 days. +2. Turns those readings into a go / no-go verdict with a 0–100 score and the reasoning behind it. +3. Tells you about it without being opened — a Sunday-evening outlook for the week ahead and a + go/no-go alert on the morning itself. + +## Verdicts + +Each spot and each day gets a `Verdict`: a suitability band, a score, and three lists of reasons. + +| Band | Meaning | +| --- | --- | +| **Ideal** | Score ≥ 85 | +| **Bueno** | Score ≥ 70 | +| **Regular** | Score ≥ your configured minimum | +| **Flojo** | Below your configured minimum | +| **No ir** | A hard limit was crossed — the score is irrelevant | +| **Sin datos** | Nothing measurable was available | + +Two kinds of rule produce it: + +- **Hard limits** are deal-breakers. Cross one and the day is *No ir* no matter how good + everything else looks — e.g. ski wind above 70 km/h. Each has its own on/off switch, so you + can demote it to an ordinary scoring factor instead of deleting it. +- **Preferences** shape the score. Each available reading contributes a weighted 0–1 sub-score; + readings that are missing are skipped rather than counted as zero. + +Every reason is written out with the actual number and the limit it broke +("Viento 82 km/h (límite 70 km/h): remontes en riesgo de cierre"), so both the card and the +notification explain themselves. + +### What you can configure + +All of it lives in **Ajustes**, in metric units internally so switching display units never +changes a rule. Per sport there is also a *Restaurar* button. + +**Surf** — ideal wave range, hard min/max wave, ideal and hard-minimum period, ideal and hard +maximum wind, hard minimum sea temperature, and whether offshore wind is rewarded. + +**Windsurf** — ideal wind range, hard minimum *and* maximum wind (too little wind is its own +deal-breaker), maximum gust spread (gust minus average — how gusty the day is), hard maximum +wave, hard minimum air and sea temperature, and whether cross-shore wind is rewarded. + +**Ski** — **espesor recomendado** (the depth that scores full marks) and a hard minimum depth +below it, fresh-snow target, ideal and hard-maximum wind, hard-maximum gusts, ideal temperature +range with hard limits either side, maximum rain, minimum visibility, and a maximum freezing +level (above the resort it rains instead of snowing). + +**Global** — the minimum score at which the app says "sí puedes ir", the four unit choices, and +the alert schedule. + +**Per spot** (the ⚙ icon on each card) — the **coast orientation**, which is what lets the app +tell offshore from onshore wind, and for ski resorts the **altitude** the forecast is taken at +(leave the geocoder's village altitude and you will see rain where the slopes get snow). + +## Alerts + +Both are self-renewing one-shot WorkManager jobs rather than periodic requests: periodic work +drifts and cannot be pinned to a wall-clock time, and "domingo por la tarde" has to actually +land on Sunday afternoon. Each worker re-arms the next run when it finishes, so the time stays +exact across DST changes and a settings change takes effect immediately. + +- **Previsión semanal** — default Sunday 18:00, configurable to any weekday and time. One + notification per sport covering **every** saved place, listing the days of the coming week + worth going and how good each is. Today is excluded; the point is the week ahead. +- **Aviso del día** — default 07:00, configurable. Per spot: "✅ Hoy sí" or "🚫 Hoy no", with + the reasons on expand. By default it reports no-go days too — knowing not to drive two hours + is worth as much as knowing to go — and there is a switch to only hear the good news. + +Alerts are on for every spot by default; the switch on each card opts one out. **Probar diario** +and **Probar semanal** in settings fire one immediately so you can see what it looks like. + +## Data shown + +Everything below is rendered as labelled chips, grouped with the section that matters most to +the sport first. Anything the model does not publish for a location is omitted rather than shown +blank. Tap **Ver todos los datos** on a card for the full set, or any day in the strip for that +day's full set plus an hour-by-hour breakdown. + +- **Sea** — wave height, period and direction; swell height, period, peak period and direction; + wind-wave height and period; sea surface temperature; ocean current speed and direction; sea + level. Plus **tide turns** (high/low with time and height), derived from the hourly sea-level + curve. +- **Wind** — speed, gusts, direction as a compass point, and whether it is offshore, cross-shore + or onshore for that spot. +- **Snow** — snowpack depth, fresh snow now and today, freezing level, spot altitude. +- **Air** — sky description, temperature, apparent temperature, humidity, cloud cover, + precipitation and probability, precipitation hours, pressure, visibility, UV index. +- **Sun** — sunrise, sunset, daylight hours, sunshine hours, peak UV. + +The card also shows the **best window of the day**: the longest unbroken run of hours that +clears your rules. + +## Weather provider + +**[Open-Meteo](https://open-meteo.com/)**, free tier, no API key and no account. + +- `geocoding-api.open-meteo.com` — place name → lat/lon/elevation. +- `api.open-meteo.com/v1/forecast` — atmosphere. Fetched for **every** sport, including surf: + wind is what separates a clean wave from a mess. One request returns current, hourly and + daily, so a spot costs one round trip instead of three. +- `marine-api.open-meteo.com/v1/marine` — waves, swell, sea temperature and sea level. Added + for surf and windsurf only. + +The two are fetched in parallel and fail independently: if the marine model is quiet the spot +still renders its weather with a warning, and vice versa. + +Two caveats worth knowing. Snow depth is the **model's** snowpack estimate, not a resort report — +treat it as a good indicator, not a piste bulletin. And Open-Meteo has no tide table on the free +tier, so tide turns are local extrema of the hourly sea-level (MSL) series, which tracks the real +tide closely but is not an official prediction. + +If you later want higher rate limits or commercial use, Open-Meteo sells an API-key plan — swap +the base URLs in [`NetworkModule.kt`](app/src/main/java/com/zenvairo/sportssuitability/data/remote/NetworkModule.kt) +for the `customer-*` endpoints and add the key as a query param. + +## Architecture + +- **UI** — Compose + Material 3, one `MainActivity` with a bottom bar per sport + ([`ui/screens/SportScreen.kt`](app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SportScreen.kt)), + pull-to-refresh, expandable cards and a per-day detail dialog. +- **Rules engine** — + [`data/repository/Suitability.kt`](app/src/main/java/com/zenvairo/sportssuitability/data/repository/Suitability.kt). + Plain Kotlin with no Compose dependency (colours live in `ui/SuitabilityUi.kt`), so it is unit + tested directly. Everything is scored through one sport-neutral `RuleInput`, which is why + "now", each day and each hour all go through identical code. +- **Settings** — the thresholds are described once as a list of `Tunable`s in + [`data/prefs/Tunables.kt`](app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Tunables.kt). + The settings screen renders from that list and DataStore persists from it, so adding a new + threshold means adding one entry and nothing else. +- **Persistence** — Room for saved spots (schema v4, migrations 1→2→3→4), DataStore for settings. +- **Network** — Retrofit + kotlinx.serialization, every field nullable so a missing variable + degrades to "no data" for that metric rather than failing the request. + +### A note on units + +Instantaneous and accumulated readings are not interchangeable. `rain` is mm **per hour** while +`rain_sum` is mm **per day**, and the thresholds are daily figures — so the "today" verdict takes +wind, waves, temperature and snowpack from the current snapshot but rain and fresh snow from the +day's totals. Hourly verdicts do the same with their parent day. Getting this wrong makes every +precipitation rule silently far too lenient. + +## Building + +```bash +./gradlew :app:assembleDebug +``` + +Open the folder in **Android Studio (Koala or newer)**, let Gradle sync (JDK 17), and run on a +device or emulator with API 26+. + +## Tests + +```bash +./gradlew :app:testDebugUnitTest +``` + +29 JVM unit tests covering the rules engine (hard limits blocking and unblocking, disabling a +limit, the recommended-depth curve, the minimum-score threshold, offshore/onshore detection, +daily-vs-instantaneous unit handling, best-window detection) and the alert scheduler (that the +weekly job lands on the configured evening and rolls over correctly). diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..69ebd19 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,85 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") + id("org.jetbrains.kotlin.plugin.compose") + id("org.jetbrains.kotlin.plugin.serialization") + id("com.google.devtools.ksp") +} + +android { + namespace = "com.zenvairo.sportssuitability" + compileSdk = 36 + + defaultConfig { + applicationId = "com.zenvairo.sportssuitability" + minSdk = 26 + targetSdk = 36 + versionCode = 1 + versionName = "1.0" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = "17" + } + + buildFeatures { + compose = true + } + + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } +} + +dependencies { + val composeBom = platform("androidx.compose:compose-bom:2026.06.01") + implementation(composeBom) + androidTestImplementation(composeBom) + + implementation("androidx.core:core-ktx:1.17.0") + implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.9.4") + implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.4") + implementation("androidx.activity:activity-compose:1.10.1") + + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.ui:ui-graphics") + implementation("androidx.compose.ui:ui-tooling-preview") + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.material:material-icons-extended") + + // Networking + implementation("com.squareup.retrofit2:retrofit:2.11.0") + implementation("com.squareup.retrofit2:converter-kotlinx-serialization:2.11.0") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0") + + // Persistence (saved spots) + implementation("androidx.room:room-runtime:2.8.4") + implementation("androidx.room:room-ktx:2.8.4") + ksp("androidx.room:room-compiler:2.8.4") + + // Datastore for lightweight prefs (units, etc.) + implementation("androidx.datastore:datastore-preferences:1.2.1") + + // Daily suitability alerts + implementation("androidx.work:work-runtime-ktx:2.10.0") + + debugImplementation("androidx.compose.ui:ui-tooling") + + // Unit tests for the suitability rules engine (plain JVM, no Android runtime needed) + testImplementation("junit:junit:4.13.2") +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..fb164d6 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1 @@ +# Add project specific ProGuard rules here. diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..0836015 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/zenvairo/sportssuitability/MainActivity.kt b/app/src/main/java/com/zenvairo/sportssuitability/MainActivity.kt new file mode 100644 index 0000000..7d4e07c --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/MainActivity.kt @@ -0,0 +1,164 @@ +package com.zenvairo.sportssuitability + +import android.Manifest +import android.content.pm.PackageManager +import android.os.Build +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.viewModels +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.NavigationBar +import androidx.compose.material3.NavigationBarItem +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.core.content.ContextCompat +import com.zenvairo.sportssuitability.data.local.AppDatabase +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.SettingsRepository +import com.zenvairo.sportssuitability.data.repository.SpotsRepository +import com.zenvairo.sportssuitability.ui.SpotsViewModel +import com.zenvairo.sportssuitability.ui.SpotsViewModelFactory +import com.zenvairo.sportssuitability.ui.screens.SettingsScreen +import com.zenvairo.sportssuitability.ui.screens.SportScreen +import com.zenvairo.sportssuitability.ui.theme.SportsSuitabilityTheme +import com.zenvairo.sportssuitability.ui.uiInfo + +class MainActivity : ComponentActivity() { + + private val viewModel: SpotsViewModel by viewModels { + SpotsViewModelFactory( + SpotsRepository(AppDatabase.get(applicationContext)), + SettingsRepository(applicationContext), + applicationContext + ) + } + + private val requestNotificationPermission = + registerForActivityResult(ActivityResultContracts.RequestPermission()) { } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != + PackageManager.PERMISSION_GRANTED + ) { + requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS) + } + setContent { + SportsSuitabilityTheme { + Surface(color = MaterialTheme.colorScheme.background) { + AppRoot(viewModel) + } + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun AppRoot(viewModel: SpotsViewModel) { + var selectedSport by remember { mutableStateOf(SportType.SURF) } + var showSettings by remember { mutableStateOf(false) } + val uiStateBySport by viewModel.uiStateBySport.collectAsState() + val searchState by viewModel.search.collectAsState() + val settings by viewModel.settings.collectAsState() + + BackHandler(enabled = showSettings) { showSettings = false } + + Scaffold( + topBar = { + TopAppBar( + title = { Text(if (showSettings) "Ajustes" else selectedSport.uiInfo().label) }, + navigationIcon = { + if (showSettings) { + IconButton(onClick = { showSettings = false }) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Volver") + } + } + }, + actions = { + if (!showSettings) { + IconButton(onClick = { viewModel.refreshSport(selectedSport) }) { + Icon(Icons.Filled.Refresh, contentDescription = "Actualizar") + } + IconButton(onClick = { showSettings = true }) { + Icon(Icons.Filled.Settings, contentDescription = "Ajustes") + } + } + } + ) + }, + bottomBar = { + if (!showSettings) { + NavigationBar { + SportType.values().forEach { sport -> + val info = sport.uiInfo() + NavigationBarItem( + selected = selectedSport == sport, + onClick = { selectedSport = sport }, + icon = { Icon(info.icon, contentDescription = info.label) }, + label = { Text(info.label) } + ) + } + } + } + } + ) { padding -> + Box( + Modifier + .padding(padding) + .fillMaxSize() + ) { + if (showSettings) { + SettingsScreen( + settings = settings, + onUpdate = viewModel::updateSettings, + onResetSport = viewModel::resetSportDefaults, + onTestDailyAlert = viewModel::sendTestDailyAlert, + onTestWeeklyAlert = viewModel::sendTestWeeklyAlert + ) + } else { + val state = uiStateBySport[selectedSport] + SportScreen( + sportType = selectedSport, + conditions = state?.conditions.orEmpty(), + isLoading = state?.isLoading ?: false, + isRefreshing = state?.isRefreshing ?: false, + searchState = searchState, + settings = settings, + onQueryChanged = viewModel::onSearchQueryChanged, + onSearch = viewModel::searchLocations, + onPick = { result -> viewModel.addSpot(result, selectedSport) }, + onRemove = viewModel::removeSpot, + onToggleAlerts = viewModel::toggleAlerts, + onSetCoastFacing = viewModel::setCoastFacing, + onSetAltitude = viewModel::setAltitude, + onRefresh = { viewModel.refreshSport(selectedSport) }, + onDismissSearch = viewModel::clearSearch + ) + } + } + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/SportsSuitabilityApp.kt b/app/src/main/java/com/zenvairo/sportssuitability/SportsSuitabilityApp.kt new file mode 100644 index 0000000..aeedac1 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/SportsSuitabilityApp.kt @@ -0,0 +1,27 @@ +package com.zenvairo.sportssuitability + +import android.app.Application +import com.zenvairo.sportssuitability.alerts.AlertScheduler +import com.zenvairo.sportssuitability.alerts.ensureNotificationChannels +import com.zenvairo.sportssuitability.data.prefs.SettingsRepository +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch + +class SportsSuitabilityApp : Application() { + + private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + override fun onCreate() { + super.onCreate() + ensureNotificationChannels(this) + // Re-arm on every cold start: the workers survive reboots via WorkManager, but this + // also picks up any schedule the user changed while the app was not running. + appScope.launch { + val alerts = SettingsRepository(this@SportsSuitabilityApp).settings.first().alerts + AlertScheduler.rescheduleAll(this@SportsSuitabilityApp, alerts) + } + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/alerts/AlertScheduler.kt b/app/src/main/java/com/zenvairo/sportssuitability/alerts/AlertScheduler.kt new file mode 100644 index 0000000..eff4eb3 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/alerts/AlertScheduler.kt @@ -0,0 +1,119 @@ +package com.zenvairo.sportssuitability.alerts + +import android.content.Context +import androidx.work.Constraints +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import com.zenvairo.sportssuitability.data.prefs.AlertSettings +import java.time.DayOfWeek +import java.time.Duration +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime + +/** + * Schedules the two alerts as self-renewing one-shot jobs rather than periodic work. + * + * WorkManager's periodic requests drift and cannot be pinned to a wall-clock time, which + * matters here: "domingo por la tarde" has to actually land on Sunday afternoon. Each worker + * re-arms the next run when it finishes, so the time stays exact across DST changes and the + * user can move the hour in settings and have it take effect immediately. + */ +object AlertScheduler { + + const val DAILY_WORK_NAME = "daily_suitability_alert" + const val WEEKLY_WORK_NAME = "weekly_forecast_alert" + + /** + * The periodic request used before the switch to self-renewing one-shot work. Installs + * upgrading from that version still have it enqueued, and it runs the same worker — so + * without cancelling it the morning alert would fire twice. + */ + private const val LEGACY_PERIODIC_WORK_NAME = "daily_suitability_alert_check" + + private val networkRequired = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + + fun rescheduleAll(context: Context, alerts: AlertSettings) { + WorkManager.getInstance(context).cancelUniqueWork(LEGACY_PERIODIC_WORK_NAME) + scheduleDaily(context, alerts) + scheduleWeekly(context, alerts) + } + + fun scheduleDaily(context: Context, alerts: AlertSettings, from: LocalDateTime = LocalDateTime.now()) { + val workManager = WorkManager.getInstance(context) + if (!alerts.dailyEnabled) { + workManager.cancelUniqueWork(DAILY_WORK_NAME) + return + } + val delay = untilNextDailyRun(alerts, from) + workManager.enqueueUniqueWork( + DAILY_WORK_NAME, + ExistingWorkPolicy.REPLACE, + OneTimeWorkRequestBuilder() + .setInitialDelay(delay) + .setConstraints(networkRequired) + .build() + ) + } + + fun scheduleWeekly(context: Context, alerts: AlertSettings, from: LocalDateTime = LocalDateTime.now()) { + val workManager = WorkManager.getInstance(context) + if (!alerts.weeklyEnabled) { + workManager.cancelUniqueWork(WEEKLY_WORK_NAME) + return + } + val delay = untilNextWeeklyRun(alerts, from) + workManager.enqueueUniqueWork( + WEEKLY_WORK_NAME, + ExistingWorkPolicy.REPLACE, + OneTimeWorkRequestBuilder() + .setInitialDelay(delay) + .setConstraints(networkRequired) + .build() + ) + } + + /** Next occurrence of the configured time of day, today if it has not passed yet. */ + fun untilNextDailyRun(alerts: AlertSettings, from: LocalDateTime): Duration { + val time = LocalTime.of(alerts.dailyHour, alerts.dailyMinute) + var next = LocalDateTime.of(from.toLocalDate(), time) + if (!next.isAfter(from)) next = next.plusDays(1) + return Duration.between(from, next) + } + + /** Next occurrence of the configured weekday and time, this week if it is still ahead. */ + fun untilNextWeeklyRun(alerts: AlertSettings, from: LocalDateTime): Duration { + val target = DayOfWeek.of(alerts.weeklyDayOfWeek) + val time = LocalTime.of(alerts.weeklyHour, alerts.weeklyMinute) + val daysAhead = ((target.value - from.dayOfWeek.value) + 7) % 7 + var next = LocalDateTime.of(from.toLocalDate().plusDays(daysAhead.toLong()), time) + if (!next.isAfter(from)) { + next = LocalDateTime.of(next.toLocalDate().plusWeeks(1), time) + } + return Duration.between(from, next) + } +} + +/** Sunday-first-in-Spanish weekday names, indexed by [DayOfWeek.getValue]. */ +fun dayOfWeekLabel(isoDay: Int): String = when (isoDay) { + 1 -> "Lunes" + 2 -> "Martes" + 3 -> "Miércoles" + 4 -> "Jueves" + 5 -> "Viernes" + 6 -> "Sábado" + else -> "Domingo" +} + +/** Short label used in the week strip, e.g. "Hoy", "Mañana", "Vie". */ +fun shortDayLabel(date: String, today: LocalDate = LocalDate.now()): String = runCatching { + when (val parsed = LocalDate.parse(date)) { + today -> "Hoy" + today.plusDays(1) -> "Mañana" + else -> dayOfWeekLabel(parsed.dayOfWeek.value).take(3) + } +}.getOrElse { date.takeLast(5) } diff --git a/app/src/main/java/com/zenvairo/sportssuitability/alerts/DailyAlertWorker.kt b/app/src/main/java/com/zenvairo/sportssuitability/alerts/DailyAlertWorker.kt new file mode 100644 index 0000000..79c5a26 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/alerts/DailyAlertWorker.kt @@ -0,0 +1,87 @@ +package com.zenvairo.sportssuitability.alerts + +import android.content.Context +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import com.zenvairo.sportssuitability.data.local.AppDatabase +import com.zenvairo.sportssuitability.data.local.Spot +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.prefs.SettingsRepository +import com.zenvairo.sportssuitability.data.repository.SpotConditions +import com.zenvairo.sportssuitability.data.repository.SpotsRepository +import com.zenvairo.sportssuitability.data.repository.Verdict +import com.zenvairo.sportssuitability.data.repository.dailyVerdict +import com.zenvairo.sportssuitability.data.repository.nowVerdict +import com.zenvairo.sportssuitability.ui.uiInfo +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext + +/** + * Runs at the configured hour every morning and answers, per spot, "¿hoy puedo ir?". + * Unless the user opted into good-news-only, a no-go is reported too, with the reason — + * knowing not to drive two hours is worth as much as knowing to go. + */ +class DailyAlertWorker(context: Context, params: WorkerParameters) : + CoroutineWorker(context, params) { + + override suspend fun doWork(): Result = withContext(Dispatchers.IO) { + val settings = SettingsRepository(applicationContext).settings.first() + try { + ensureNotificationChannels(applicationContext) + val repository = SpotsRepository(AppDatabase.get(applicationContext)) + repository.spotsWithAlerts().forEach { spot -> + notifyFor(repository.fetchConditions(spot), spot, settings) + } + Result.success() + } catch (e: Exception) { + // Not a retry: the finally block already queues tomorrow's run, and a WorkManager + // retry would race with it over the same unique work name. + Result.success() + } finally { + // Re-arm tomorrow's run whatever happened, so one bad night doesn't end the series. + AlertScheduler.scheduleDaily(applicationContext, settings.alerts) + } + } + + private fun notifyFor(conditions: SpotConditions, spot: Spot, settings: AppSettings) { + if (conditions.error != null) return + // Prefer today's daily figures: at 07:00 the "current" snapshot says little about + // whether the afternoon is worth the drive. + val verdict = conditions.today?.let { conditions.dailyVerdict(it, settings) } + ?: conditions.nowVerdict(settings) + + if (settings.alerts.dailyOnlyWhenGood && !verdict.canGo) return + if (verdict.score == null && verdict.blockers.isEmpty()) return + + val sportLabel = spot.sportType.uiInfo().label + val title = if (verdict.canGo) "✅ Hoy sí — ${spot.name}" else "🚫 Hoy no — ${spot.name}" + postNotification( + context = applicationContext, + channelId = DAILY_CHANNEL_ID, + notificationId = spot.id.toInt(), + title = title, + summary = verdict.headline, + body = buildBody(sportLabel, verdict) + ) + } + + private fun buildBody(sportLabel: String, verdict: Verdict): String = buildString { + append(sportLabel) + append(" · ") + append(verdict.suitability.label) + verdict.score?.let { append(" (") ; append(it) ; append("/100)") } + if (verdict.blockers.isNotEmpty()) { + append("\n\nPor qué no:") + verdict.blockers.forEach { append("\n• ").append(it) } + } + if (verdict.highlights.isNotEmpty()) { + append("\n\nA favor:") + verdict.highlights.forEach { append("\n• ").append(it) } + } + if (verdict.warnings.isNotEmpty()) { + append("\n\nOjo:") + verdict.warnings.forEach { append("\n• ").append(it) } + } + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/alerts/NotificationHelper.kt b/app/src/main/java/com/zenvairo/sportssuitability/alerts/NotificationHelper.kt new file mode 100644 index 0000000..fd26449 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/alerts/NotificationHelper.kt @@ -0,0 +1,79 @@ +package com.zenvairo.sportssuitability.alerts + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.ActivityCompat +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import com.zenvairo.sportssuitability.MainActivity + +const val DAILY_CHANNEL_ID = "daily_suitability_alerts" +const val WEEKLY_CHANNEL_ID = "weekly_forecast_alerts" + +private const val NOTIFICATION_GROUP = "com.zenvairo.sportssuitability.CONDITIONS" + +fun ensureNotificationChannels(context: Context) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val manager = context.getSystemService(NotificationManager::class.java) ?: return + manager.createNotificationChannel( + NotificationChannel( + DAILY_CHANNEL_ID, + "Aviso del día", + NotificationManager.IMPORTANCE_DEFAULT + ).apply { description = "Te dice cada mañana si hoy puedes ir a cada sitio guardado" } + ) + manager.createNotificationChannel( + NotificationChannel( + WEEKLY_CHANNEL_ID, + "Previsión semanal", + NotificationManager.IMPORTANCE_DEFAULT + ).apply { description = "Resumen de la semana que viene, con los mejores días de cada sitio" } + ) +} + +private fun canPostNotifications(context: Context): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + ActivityCompat.checkSelfPermission( + context, + android.Manifest.permission.POST_NOTIFICATIONS + ) == PackageManager.PERMISSION_GRANTED + +private fun openAppIntent(context: Context, requestCode: Int): PendingIntent = + PendingIntent.getActivity( + context, + requestCode, + Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + +/** + * Posts one notification, expanding to [body] when the user pulls it down. + * Silently no-ops when the user has not granted the notification permission. + */ +fun postNotification( + context: Context, + channelId: String, + notificationId: Int, + title: String, + summary: String, + body: String = summary +) { + if (!canPostNotifications(context)) return + val notification = NotificationCompat.Builder(context, channelId) + .setSmallIcon(android.R.drawable.ic_dialog_info) + .setContentTitle(title) + .setContentText(summary) + .setStyle(NotificationCompat.BigTextStyle().bigText(body)) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .setGroup(NOTIFICATION_GROUP) + .setContentIntent(openAppIntent(context, notificationId)) + .setAutoCancel(true) + .build() + NotificationManagerCompat.from(context).notify(notificationId, notification) +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/alerts/WeeklyForecastWorker.kt b/app/src/main/java/com/zenvairo/sportssuitability/alerts/WeeklyForecastWorker.kt new file mode 100644 index 0000000..e72c83e --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/alerts/WeeklyForecastWorker.kt @@ -0,0 +1,106 @@ +package com.zenvairo.sportssuitability.alerts + +import android.content.Context +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import com.zenvairo.sportssuitability.data.local.AppDatabase +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.prefs.SettingsRepository +import com.zenvairo.sportssuitability.data.repository.SpotConditions +import com.zenvairo.sportssuitability.data.repository.SpotsRepository +import com.zenvairo.sportssuitability.data.repository.dailyVerdict +import com.zenvairo.sportssuitability.ui.uiInfo +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext +import java.time.LocalDate + +/** Notification ids for the weekly digest, kept clear of the per-spot daily ids. */ +private const val WEEKLY_NOTIFICATION_ID_BASE = 900_000 + +/** + * The Sunday-evening digest: one notification per sport, listing every saved place and the + * days of the coming week that are actually worth going, so the week can be planned in one go. + */ +class WeeklyForecastWorker(context: Context, params: WorkerParameters) : + CoroutineWorker(context, params) { + + override suspend fun doWork(): Result = withContext(Dispatchers.IO) { + val settings = SettingsRepository(applicationContext).settings.first() + try { + ensureNotificationChannels(applicationContext) + val repository = SpotsRepository(AppDatabase.get(applicationContext)) + val spots = repository.allSpots() + if (spots.isEmpty()) return@withContext Result.success() + + val conditions = coroutineScope { + spots.map { async { repository.fetchConditions(it) } }.awaitAll() + } + + conditions.groupBy { it.spot.sportType }.forEach { (sport, forSport) -> + notifySport(sport, forSport, settings) + } + Result.success() + } catch (e: Exception) { + // See DailyAlertWorker: the finally block re-arms, so a retry would only race it. + Result.success() + } finally { + AlertScheduler.scheduleWeekly(applicationContext, settings.alerts) + } + } + + private fun notifySport( + sport: SportType, + conditions: List, + settings: AppSettings + ) { + val today = LocalDate.now() + val label = sport.uiInfo().label + var anyGoodDay = false + + val lines = conditions.map { spotConditions -> + val name = spotConditions.spot.name + if (spotConditions.error != null) return@map "$name: sin datos" + + // Skip today — this runs on Sunday evening, the point is the week ahead. + val upcoming = spotConditions.days.filter { day -> + runCatching { LocalDate.parse(day.date).isAfter(today) }.getOrDefault(false) + } + val good = upcoming + .map { it to spotConditions.dailyVerdict(it, settings) } + .filter { (_, verdict) -> verdict.canGo } + .sortedByDescending { (_, verdict) -> verdict.score ?: 0 } + .take(3) + + if (good.isEmpty()) { + "$name: ningún día recomendable" + } else { + anyGoodDay = true + val days = good.joinToString(", ") { (day, verdict) -> + "${shortDayLabel(day.date, today)} ${verdict.suitability.label.lowercase()}" + + (verdict.score?.let { " ($it)" } ?: "") + } + "$name: $days" + } + } + + val summary = if (anyGoodDay) { + "Hay días buenos esta semana" + } else { + "Semana floja: ningún día llega al mínimo" + } + + postNotification( + context = applicationContext, + channelId = WEEKLY_CHANNEL_ID, + notificationId = WEEKLY_NOTIFICATION_ID_BASE + sport.ordinal, + title = "$label — previsión de la semana", + summary = summary, + body = lines.joinToString("\n") + ) + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/local/AppDatabase.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/local/AppDatabase.kt new file mode 100644 index 0000000..c6858d2 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/local/AppDatabase.kt @@ -0,0 +1,62 @@ +package com.zenvairo.sportssuitability.data.local + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.TypeConverter +import androidx.room.TypeConverters +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +class SportTypeConverters { + @TypeConverter + fun fromSportType(value: SportType): String = value.name + + @TypeConverter + fun toSportType(value: String): SportType = SportType.valueOf(value) +} + +private val MIGRATION_1_2 = object : Migration(1, 2) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE spots ADD COLUMN alertsEnabled INTEGER NOT NULL DEFAULT 0") + } +} + +private val MIGRATION_2_3 = object : Migration(2, 3) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE spots ADD COLUMN coastFacingDeg REAL") + db.execSQL("ALTER TABLE spots ADD COLUMN altitudeM REAL") + } +} + +/** + * The morning alert used to be opt-in per spot and defaulted to off, which meant a fresh + * install (or an upgrade) never notified anything until the user found the switch. Alerts are + * now on by default, so existing spots are opted in too; the card switch still turns them off. + */ +private val MIGRATION_3_4 = object : Migration(3, 4) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("UPDATE spots SET alertsEnabled = 1") + } +} + +@Database(entities = [Spot::class], version = 4, exportSchema = false) +@TypeConverters(SportTypeConverters::class) +abstract class AppDatabase : RoomDatabase() { + abstract fun spotDao(): SpotDao + + companion object { + @Volatile private var instance: AppDatabase? = null + + fun get(context: Context): AppDatabase = + instance ?: synchronized(this) { + instance ?: Room.databaseBuilder( + context.applicationContext, + AppDatabase::class.java, + "sports_suitability.db" + ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4) + .build().also { instance = it } + } + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/local/Spot.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/local/Spot.kt new file mode 100644 index 0000000..854da67 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/local/Spot.kt @@ -0,0 +1,32 @@ +package com.zenvairo.sportssuitability.data.local + +import androidx.room.Entity +import androidx.room.PrimaryKey + +enum class SportType { SURF, WINDSURF, SKI } + +/** + * A saved place the user cares about. + * + * [coastFacingDeg] is the compass bearing the coast looks towards (0 = the beach faces + * north, so you look north at the sea). It is optional and only meaningful for water + * sports; when set, the app can tell offshore from onshore wind, which is the single + * biggest quality factor for surf. + * + * [baseAltitudeM] is only meaningful for ski resorts: forecasts are requested at that + * elevation instead of the geocoder's village-level altitude, which otherwise reports + * rain where the slopes get snow. + */ +@Entity(tableName = "spots") +data class Spot( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val name: String, + val region: String?, + val latitude: Double, + val longitude: Double, + val sportType: SportType, + /** Opted into the morning go/no-go alert. On by default; the card switch opts out. */ + val alertsEnabled: Boolean = true, + val coastFacingDeg: Double? = null, + val altitudeM: Double? = null +) diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/local/SpotDao.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/local/SpotDao.kt new file mode 100644 index 0000000..149df03 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/local/SpotDao.kt @@ -0,0 +1,34 @@ +package com.zenvairo.sportssuitability.data.local + +import androidx.room.Dao +import androidx.room.Delete +import androidx.room.Insert +import androidx.room.Query +import kotlinx.coroutines.flow.Flow + +@Dao +interface SpotDao { + @Query("SELECT * FROM spots WHERE sportType = :sportType ORDER BY name") + fun observeBySport(sportType: SportType): Flow> + + @Insert + suspend fun insert(spot: Spot): Long + + @Delete + suspend fun delete(spot: Spot) + + @Query("UPDATE spots SET alertsEnabled = :enabled WHERE id = :spotId") + suspend fun setAlertsEnabled(spotId: Long, enabled: Boolean) + + @Query("UPDATE spots SET coastFacingDeg = :facingDeg WHERE id = :spotId") + suspend fun setCoastFacing(spotId: Long, facingDeg: Double?) + + @Query("UPDATE spots SET altitudeM = :altitudeM WHERE id = :spotId") + suspend fun setAltitude(spotId: Long, altitudeM: Double?) + + @Query("SELECT * FROM spots WHERE alertsEnabled = 1 ORDER BY sportType, name") + suspend fun spotsWithAlerts(): List + + @Query("SELECT * FROM spots ORDER BY sportType, name") + suspend fun allSpots(): List +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/AppSettings.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/AppSettings.kt new file mode 100644 index 0000000..9fb8971 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/AppSettings.kt @@ -0,0 +1,97 @@ +package com.zenvairo.sportssuitability.data.prefs + +/** + * A deal-breaker threshold. When [enabled] and crossed, the day is rated "No ir" no matter + * how good everything else looks — e.g. ski wind above 70 km/h closes the lifts. + * Turning it off downgrades the check to an ordinary scoring factor. + */ +data class Limit(val enabled: Boolean, val value: Double) + +/** + * Surf rules. "Ideal" bounds shape the score; "hard" limits can veto the day outright. + * Wave figures are significant height in metres, wind in km/h, period in seconds. + */ +data class SurfRules( + val waveIdealMinM: Double = 0.8, + val waveIdealMaxM: Double = 2.5, + val waveHardMinM: Limit = Limit(enabled = true, value = 0.4), + val waveHardMaxM: Limit = Limit(enabled = true, value = 4.0), + val periodIdealMinS: Double = 9.0, + val periodHardMinS: Limit = Limit(enabled = false, value = 6.0), + val windIdealMaxKmh: Double = 15.0, + val windHardMaxKmh: Limit = Limit(enabled = true, value = 40.0), + val seaTempHardMinC: Limit = Limit(enabled = false, value = 12.0), + /** Reward offshore wind (needs the spot's coast orientation to be set). */ + val preferOffshore: Boolean = true +) + +/** Windsurf rules: it is the only sport where too *little* wind is itself a deal-breaker. */ +data class WindsurfRules( + val windIdealMinKmh: Double = 25.0, + val windIdealMaxKmh: Double = 45.0, + val windHardMinKmh: Limit = Limit(enabled = true, value = 16.0), + val windHardMaxKmh: Limit = Limit(enabled = true, value = 65.0), + /** Gust minus average wind: a big spread means unrideable, gusty air. */ + val gustSpreadHardMaxKmh: Limit = Limit(enabled = true, value = 25.0), + val waveHardMaxM: Limit = Limit(enabled = false, value = 2.5), + val airTempHardMinC: Limit = Limit(enabled = false, value = 5.0), + val seaTempHardMinC: Limit = Limit(enabled = false, value = 10.0), + /** Reward side / side-onshore wind, penalise straight offshore (it blows you out to sea). */ + val preferSideShore: Boolean = true +) + +/** + * Ski rules. [snowDepthRecommendedCm] is the configurable "espesor recomendado": at or above + * it the snowpack scores full marks, below it the score tapers off towards + * [snowDepthHardMinCm], which vetoes the day when enabled. + */ +data class SkiRules( + val snowDepthRecommendedCm: Double = 60.0, + val snowDepthHardMinCm: Limit = Limit(enabled = true, value = 20.0), + val freshSnowIdealCm: Double = 10.0, + val windIdealMaxKmh: Double = 30.0, + val windHardMaxKmh: Limit = Limit(enabled = true, value = 70.0), + val gustHardMaxKmh: Limit = Limit(enabled = true, value = 90.0), + val tempIdealMinC: Double = -12.0, + val tempIdealMaxC: Double = 2.0, + val tempHardMinC: Limit = Limit(enabled = true, value = -20.0), + val tempHardMaxC: Limit = Limit(enabled = true, value = 8.0), + val rainHardMaxMm: Limit = Limit(enabled = true, value = 8.0), + val visibilityHardMinM: Limit = Limit(enabled = true, value = 300.0), + /** Freezing level above this means rain rather than snow on the slopes. */ + val freezingLevelHardMaxM: Limit = Limit(enabled = false, value = 2400.0) +) + +/** When and how the app is allowed to interrupt you. */ +data class AlertSettings( + val dailyEnabled: Boolean = true, + val dailyHour: Int = 7, + val dailyMinute: Int = 0, + /** When false, the morning alert also tells you when a spot is a no-go. */ + val dailyOnlyWhenGood: Boolean = false, + val weeklyEnabled: Boolean = true, + /** ISO day of week, 1 = Monday … 7 = Sunday. */ + val weeklyDayOfWeek: Int = 7, + val weeklyHour: Int = 18, + val weeklyMinute: Int = 0 +) + +/** + * User-configurable units, thresholds and alert schedule. + * Thresholds are always stored in the canonical metric unit (km/h, m, cm, °C, mm) + * regardless of the chosen display unit, so the rules engine never converts. + */ +data class AppSettings( + val windUnit: WindUnit = WindUnit.KMH, + val waveUnit: WaveUnit = WaveUnit.METERS, + val tempUnit: TempUnit = TempUnit.CELSIUS, + val snowUnit: SnowUnit = SnowUnit.CM, + + val surf: SurfRules = SurfRules(), + val windsurf: WindsurfRules = WindsurfRules(), + val ski: SkiRules = SkiRules(), + val alerts: AlertSettings = AlertSettings(), + + /** Score (0–100) a day must reach before the app says "sí, puedes ir". */ + val minScoreToGo: Int = 55 +) diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/SettingsRepository.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/SettingsRepository.kt new file mode 100644 index 0000000..de831c4 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/SettingsRepository.kt @@ -0,0 +1,145 @@ +package com.zenvairo.sportssuitability.data.prefs + +import android.content.Context +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.doublePreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.datastore.preferences.preferencesDataStore +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.map + +private val Context.dataStore by preferencesDataStore(name = "settings") + +private object Keys { + val WIND_UNIT = stringPreferencesKey("wind_unit") + val WAVE_UNIT = stringPreferencesKey("wave_unit") + val TEMP_UNIT = stringPreferencesKey("temp_unit") + val SNOW_UNIT = stringPreferencesKey("snow_unit") + + val SURF_PREFER_OFFSHORE = booleanPreferencesKey("surf_prefer_offshore") + val WINDSURF_PREFER_SIDESHORE = booleanPreferencesKey("windsurf_prefer_sideshore") + val MIN_SCORE_TO_GO = intPreferencesKey("min_score_to_go") + + val DAILY_ENABLED = booleanPreferencesKey("alert_daily_enabled") + val DAILY_HOUR = intPreferencesKey("alert_daily_hour") + val DAILY_MINUTE = intPreferencesKey("alert_daily_minute") + val DAILY_ONLY_GOOD = booleanPreferencesKey("alert_daily_only_good") + val WEEKLY_ENABLED = booleanPreferencesKey("alert_weekly_enabled") + val WEEKLY_DOW = intPreferencesKey("alert_weekly_dow") + val WEEKLY_HOUR = intPreferencesKey("alert_weekly_hour") + val WEEKLY_MINUTE = intPreferencesKey("alert_weekly_minute") + + fun tunableValue(id: String) = doublePreferencesKey("tunable_$id") + fun tunableEnabled(id: String) = booleanPreferencesKey("tunable_${id}_on") +} + +class SettingsRepository(private val context: Context) { + + val settings: Flow = context.dataStore.data.map { it.toAppSettings() } + + /** Applies [transform] and returns the stored result, so callers never read a stale flow. */ + suspend fun update(transform: (AppSettings) -> AppSettings): AppSettings { + lateinit var result: AppSettings + context.dataStore.edit { prefs -> + val updated = transform(prefs.toAppSettings()) + result = updated + + prefs[Keys.WIND_UNIT] = updated.windUnit.name + prefs[Keys.WAVE_UNIT] = updated.waveUnit.name + prefs[Keys.TEMP_UNIT] = updated.tempUnit.name + prefs[Keys.SNOW_UNIT] = updated.snowUnit.name + + prefs[Keys.SURF_PREFER_OFFSHORE] = updated.surf.preferOffshore + prefs[Keys.WINDSURF_PREFER_SIDESHORE] = updated.windsurf.preferSideShore + prefs[Keys.MIN_SCORE_TO_GO] = updated.minScoreToGo + + prefs[Keys.DAILY_ENABLED] = updated.alerts.dailyEnabled + prefs[Keys.DAILY_HOUR] = updated.alerts.dailyHour + prefs[Keys.DAILY_MINUTE] = updated.alerts.dailyMinute + prefs[Keys.DAILY_ONLY_GOOD] = updated.alerts.dailyOnlyWhenGood + prefs[Keys.WEEKLY_ENABLED] = updated.alerts.weeklyEnabled + prefs[Keys.WEEKLY_DOW] = updated.alerts.weeklyDayOfWeek + prefs[Keys.WEEKLY_HOUR] = updated.alerts.weeklyHour + prefs[Keys.WEEKLY_MINUTE] = updated.alerts.weeklyMinute + + allTunables.forEach { tunable -> + when (tunable) { + is ValueTunable -> prefs[Keys.tunableValue(tunable.id)] = tunable.get(updated) + is LimitTunable -> { + val limit = tunable.get(updated) + prefs[Keys.tunableValue(tunable.id)] = limit.value + prefs[Keys.tunableEnabled(tunable.id)] = limit.enabled + } + } + } + } + return result + } + + /** Restores every threshold of one sport to the app defaults, leaving units untouched. */ + suspend fun resetSportDefaults(sport: com.zenvairo.sportssuitability.data.local.SportType) { + update { current -> + val defaults = AppSettings() + tunableGroups(sport).flatMap { it.items }.fold(current) { acc, tunable -> + when (tunable) { + is ValueTunable -> tunable.set(acc, tunable.get(defaults)) + is LimitTunable -> tunable.set(acc, tunable.get(defaults)) + } + } + } + } + + private fun Preferences.toAppSettings(): AppSettings { + val defaults = AppSettings() + val base = defaults.copy( + windUnit = enumOr(Keys.WIND_UNIT, defaults.windUnit) { WindUnit.valueOf(it) }, + waveUnit = enumOr(Keys.WAVE_UNIT, defaults.waveUnit) { WaveUnit.valueOf(it) }, + tempUnit = enumOr(Keys.TEMP_UNIT, defaults.tempUnit) { TempUnit.valueOf(it) }, + snowUnit = enumOr(Keys.SNOW_UNIT, defaults.snowUnit) { SnowUnit.valueOf(it) }, + minScoreToGo = (this[Keys.MIN_SCORE_TO_GO] ?: defaults.minScoreToGo).coerceIn(0, 100), + surf = defaults.surf.copy( + preferOffshore = this[Keys.SURF_PREFER_OFFSHORE] ?: defaults.surf.preferOffshore + ), + windsurf = defaults.windsurf.copy( + preferSideShore = this[Keys.WINDSURF_PREFER_SIDESHORE] + ?: defaults.windsurf.preferSideShore + ), + alerts = AlertSettings( + dailyEnabled = this[Keys.DAILY_ENABLED] ?: defaults.alerts.dailyEnabled, + dailyHour = (this[Keys.DAILY_HOUR] ?: defaults.alerts.dailyHour).coerceIn(0, 23), + dailyMinute = (this[Keys.DAILY_MINUTE] ?: defaults.alerts.dailyMinute).coerceIn(0, 59), + dailyOnlyWhenGood = this[Keys.DAILY_ONLY_GOOD] ?: defaults.alerts.dailyOnlyWhenGood, + weeklyEnabled = this[Keys.WEEKLY_ENABLED] ?: defaults.alerts.weeklyEnabled, + weeklyDayOfWeek = (this[Keys.WEEKLY_DOW] ?: defaults.alerts.weeklyDayOfWeek).coerceIn(1, 7), + weeklyHour = (this[Keys.WEEKLY_HOUR] ?: defaults.alerts.weeklyHour).coerceIn(0, 23), + weeklyMinute = (this[Keys.WEEKLY_MINUTE] ?: defaults.alerts.weeklyMinute).coerceIn(0, 59) + ) + ) + + return allTunables.fold(base) { acc, tunable -> + val stored = this[Keys.tunableValue(tunable.id)] + when (tunable) { + is ValueTunable -> stored?.let { tunable.set(acc, it) } ?: acc + is LimitTunable -> { + val fallback = tunable.get(defaults) + tunable.set( + acc, + Limit( + enabled = this[Keys.tunableEnabled(tunable.id)] ?: fallback.enabled, + value = stored ?: fallback.value + ) + ) + } + } + } + } + + private inline fun Preferences.enumOr( + key: Preferences.Key, + fallback: T, + parse: (String) -> T + ): T = this[key]?.let { runCatching { parse(it) }.getOrNull() } ?: fallback +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Tunables.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Tunables.kt new file mode 100644 index 0000000..edff658 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Tunables.kt @@ -0,0 +1,300 @@ +package com.zenvairo.sportssuitability.data.prefs + +import com.zenvairo.sportssuitability.data.local.SportType + +/** + * A single knob of the suitability formulas, described once and reused everywhere: the + * settings screen renders from this list and [SettingsRepository] persists from it, so + * adding a new threshold means adding one entry here and nothing else. + */ +enum class TunableKind { WIND, WAVE, TEMP, SNOW, PERIOD, DISTANCE, MM } + +sealed interface Tunable { + val id: String + val label: String + val help: String? + val kind: TunableKind +} + +/** A preference that only shifts the score — it can never block a day. */ +data class ValueTunable( + override val id: String, + override val label: String, + override val help: String? = null, + override val kind: TunableKind, + val get: (AppSettings) -> Double, + val set: (AppSettings, Double) -> AppSettings +) : Tunable + +/** A deal-breaker with its own on/off switch. */ +data class LimitTunable( + override val id: String, + override val label: String, + override val help: String? = null, + override val kind: TunableKind, + val get: (AppSettings) -> Limit, + val set: (AppSettings, Limit) -> AppSettings +) : Tunable + +data class TunableGroup( + val title: String, + val description: String? = null, + val items: List +) + +fun TunableKind.suffix(settings: AppSettings): String = when (this) { + TunableKind.WIND -> settings.windUnit.suffix + TunableKind.WAVE -> settings.waveUnit.suffix + TunableKind.TEMP -> settings.tempUnit.suffix + TunableKind.SNOW -> settings.snowUnit.suffix + TunableKind.PERIOD -> "s" + TunableKind.DISTANCE -> "m" + TunableKind.MM -> "mm" +} + +/** Canonical metric value → the number shown in the text field. */ +fun TunableKind.toDisplay(value: Double, settings: AppSettings): Double = when (this) { + TunableKind.WIND -> value.kmhTo(settings.windUnit) + TunableKind.WAVE -> value.metersTo(settings.waveUnit) + TunableKind.TEMP -> value.celsiusTo(settings.tempUnit) + TunableKind.SNOW -> value.cmTo(settings.snowUnit) + TunableKind.PERIOD, TunableKind.DISTANCE, TunableKind.MM -> value +} + +/** The number the user typed → canonical metric value. */ +fun TunableKind.fromDisplay(value: Double, settings: AppSettings): Double = when (this) { + TunableKind.WIND -> value.toKmhFrom(settings.windUnit) + TunableKind.WAVE -> value.toMetersFrom(settings.waveUnit) + TunableKind.TEMP -> value.toCelsiusFrom(settings.tempUnit) + TunableKind.SNOW -> value.toCmFrom(settings.snowUnit) + TunableKind.PERIOD, TunableKind.DISTANCE, TunableKind.MM -> value +} + +private val surfGroups = listOf( + TunableGroup( + title = "Olas", + description = "El rango ideal marca la puntuación; los límites duros deciden si se puede ir.", + items = listOf( + ValueTunable( + "surf_wave_ideal_min", "Altura ideal mínima", kind = TunableKind.WAVE, + get = { it.surf.waveIdealMinM }, + set = { s, v -> s.copy(surf = s.surf.copy(waveIdealMinM = v)) } + ), + ValueTunable( + "surf_wave_ideal_max", "Altura ideal máxima", kind = TunableKind.WAVE, + get = { it.surf.waveIdealMaxM }, + set = { s, v -> s.copy(surf = s.surf.copy(waveIdealMaxM = v)) } + ), + LimitTunable( + "surf_wave_hard_min", "No ir si la ola es menor de", + help = "Por debajo de esta altura no hay ola con la que surfear.", + kind = TunableKind.WAVE, + get = { it.surf.waveHardMinM }, + set = { s, v -> s.copy(surf = s.surf.copy(waveHardMinM = v)) } + ), + LimitTunable( + "surf_wave_hard_max", "No ir si la ola supera", + kind = TunableKind.WAVE, + get = { it.surf.waveHardMaxM }, + set = { s, v -> s.copy(surf = s.surf.copy(waveHardMaxM = v)) } + ) + ) + ), + TunableGroup( + title = "Periodo del oleaje", + description = "Periodos largos = olas con más fuerza y mejor formadas.", + items = listOf( + ValueTunable( + "surf_period_ideal_min", "Periodo ideal mínimo", kind = TunableKind.PERIOD, + get = { it.surf.periodIdealMinS }, + set = { s, v -> s.copy(surf = s.surf.copy(periodIdealMinS = v)) } + ), + LimitTunable( + "surf_period_hard_min", "No ir si el periodo baja de", kind = TunableKind.PERIOD, + get = { it.surf.periodHardMinS }, + set = { s, v -> s.copy(surf = s.surf.copy(periodHardMinS = v)) } + ) + ) + ), + TunableGroup( + title = "Viento y agua", + items = listOf( + ValueTunable( + "surf_wind_ideal_max", "Viento ideal máximo", + help = "Por encima de este valor el mar empieza a desordenarse.", + kind = TunableKind.WIND, + get = { it.surf.windIdealMaxKmh }, + set = { s, v -> s.copy(surf = s.surf.copy(windIdealMaxKmh = v)) } + ), + LimitTunable( + "surf_wind_hard_max", "No ir si el viento supera", kind = TunableKind.WIND, + get = { it.surf.windHardMaxKmh }, + set = { s, v -> s.copy(surf = s.surf.copy(windHardMaxKmh = v)) } + ), + LimitTunable( + "surf_sea_temp_hard_min", "No ir si el agua baja de", kind = TunableKind.TEMP, + get = { it.surf.seaTempHardMinC }, + set = { s, v -> s.copy(surf = s.surf.copy(seaTempHardMinC = v)) } + ) + ) + ) +) + +private val windsurfGroups = listOf( + TunableGroup( + title = "Viento", + description = "En windsurf, quedarse sin viento es tan malo como que sobre.", + items = listOf( + ValueTunable( + "ws_wind_ideal_min", "Viento ideal mínimo", kind = TunableKind.WIND, + get = { it.windsurf.windIdealMinKmh }, + set = { s, v -> s.copy(windsurf = s.windsurf.copy(windIdealMinKmh = v)) } + ), + ValueTunable( + "ws_wind_ideal_max", "Viento ideal máximo", kind = TunableKind.WIND, + get = { it.windsurf.windIdealMaxKmh }, + set = { s, v -> s.copy(windsurf = s.windsurf.copy(windIdealMaxKmh = v)) } + ), + LimitTunable( + "ws_wind_hard_min", "No ir si el viento baja de", kind = TunableKind.WIND, + get = { it.windsurf.windHardMinKmh }, + set = { s, v -> s.copy(windsurf = s.windsurf.copy(windHardMinKmh = v)) } + ), + LimitTunable( + "ws_wind_hard_max", "No ir si el viento supera", kind = TunableKind.WIND, + get = { it.windsurf.windHardMaxKmh }, + set = { s, v -> s.copy(windsurf = s.windsurf.copy(windHardMaxKmh = v)) } + ), + LimitTunable( + "ws_gust_spread_hard_max", "No ir si racha − viento supera", + help = "Diferencia entre racha y viento medio: mide lo racheado que está el día.", + kind = TunableKind.WIND, + get = { it.windsurf.gustSpreadHardMaxKmh }, + set = { s, v -> s.copy(windsurf = s.windsurf.copy(gustSpreadHardMaxKmh = v)) } + ) + ) + ), + TunableGroup( + title = "Mar y temperatura", + items = listOf( + LimitTunable( + "ws_wave_hard_max", "No ir si la ola supera", kind = TunableKind.WAVE, + get = { it.windsurf.waveHardMaxM }, + set = { s, v -> s.copy(windsurf = s.windsurf.copy(waveHardMaxM = v)) } + ), + LimitTunable( + "ws_air_temp_hard_min", "No ir si el aire baja de", kind = TunableKind.TEMP, + get = { it.windsurf.airTempHardMinC }, + set = { s, v -> s.copy(windsurf = s.windsurf.copy(airTempHardMinC = v)) } + ), + LimitTunable( + "ws_sea_temp_hard_min", "No ir si el agua baja de", kind = TunableKind.TEMP, + get = { it.windsurf.seaTempHardMinC }, + set = { s, v -> s.copy(windsurf = s.windsurf.copy(seaTempHardMinC = v)) } + ) + ) + ) +) + +private val skiGroups = listOf( + TunableGroup( + title = "Nieve", + description = "El espesor recomendado es el que puntúa al 100 %; por debajo baja la nota " + + "hasta el mínimo, que ya impide ir.", + items = listOf( + ValueTunable( + "ski_depth_recommended", "Espesor recomendado", kind = TunableKind.SNOW, + get = { it.ski.snowDepthRecommendedCm }, + set = { s, v -> s.copy(ski = s.ski.copy(snowDepthRecommendedCm = v)) } + ), + LimitTunable( + "ski_depth_hard_min", "No ir si el espesor baja de", kind = TunableKind.SNOW, + get = { it.ski.snowDepthHardMinCm }, + set = { s, v -> s.copy(ski = s.ski.copy(snowDepthHardMinCm = v)) } + ), + ValueTunable( + "ski_fresh_ideal", "Nieve fresca para día ideal", kind = TunableKind.SNOW, + get = { it.ski.freshSnowIdealCm }, + set = { s, v -> s.copy(ski = s.ski.copy(freshSnowIdealCm = v)) } + ) + ) + ), + TunableGroup( + title = "Viento", + description = "Los remontes cierran con viento fuerte: este es el límite que decide el día.", + items = listOf( + ValueTunable( + "ski_wind_ideal_max", "Viento ideal máximo", kind = TunableKind.WIND, + get = { it.ski.windIdealMaxKmh }, + set = { s, v -> s.copy(ski = s.ski.copy(windIdealMaxKmh = v)) } + ), + LimitTunable( + "ski_wind_hard_max", "No ir si el viento supera", kind = TunableKind.WIND, + get = { it.ski.windHardMaxKmh }, + set = { s, v -> s.copy(ski = s.ski.copy(windHardMaxKmh = v)) } + ), + LimitTunable( + "ski_gust_hard_max", "No ir si las rachas superan", kind = TunableKind.WIND, + get = { it.ski.gustHardMaxKmh }, + set = { s, v -> s.copy(ski = s.ski.copy(gustHardMaxKmh = v)) } + ) + ) + ), + TunableGroup( + title = "Temperatura", + items = listOf( + ValueTunable( + "ski_temp_ideal_min", "Temperatura ideal mínima", kind = TunableKind.TEMP, + get = { it.ski.tempIdealMinC }, + set = { s, v -> s.copy(ski = s.ski.copy(tempIdealMinC = v)) } + ), + ValueTunable( + "ski_temp_ideal_max", "Temperatura ideal máxima", kind = TunableKind.TEMP, + get = { it.ski.tempIdealMaxC }, + set = { s, v -> s.copy(ski = s.ski.copy(tempIdealMaxC = v)) } + ), + LimitTunable( + "ski_temp_hard_min", "No ir si baja de", kind = TunableKind.TEMP, + get = { it.ski.tempHardMinC }, + set = { s, v -> s.copy(ski = s.ski.copy(tempHardMinC = v)) } + ), + LimitTunable( + "ski_temp_hard_max", "No ir si sube de", kind = TunableKind.TEMP, + get = { it.ski.tempHardMaxC }, + set = { s, v -> s.copy(ski = s.ski.copy(tempHardMaxC = v)) } + ) + ) + ), + TunableGroup( + title = "Lluvia, visibilidad y cota", + items = listOf( + LimitTunable( + "ski_rain_hard_max", "No ir si llueve más de", kind = TunableKind.MM, + get = { it.ski.rainHardMaxMm }, + set = { s, v -> s.copy(ski = s.ski.copy(rainHardMaxMm = v)) } + ), + LimitTunable( + "ski_visibility_hard_min", "No ir si la visibilidad baja de", kind = TunableKind.DISTANCE, + get = { it.ski.visibilityHardMinM }, + set = { s, v -> s.copy(ski = s.ski.copy(visibilityHardMinM = v)) } + ), + LimitTunable( + "ski_freezing_level_hard_max", "No ir si la cota de nieve sube de", + help = "Isoterma cero: si queda por encima de la estación, cae agua en vez de nieve.", + kind = TunableKind.DISTANCE, + get = { it.ski.freezingLevelHardMaxM }, + set = { s, v -> s.copy(ski = s.ski.copy(freezingLevelHardMaxM = v)) } + ) + ) + ) +) + +fun tunableGroups(sport: SportType): List = when (sport) { + SportType.SURF -> surfGroups + SportType.WINDSURF -> windsurfGroups + SportType.SKI -> skiGroups +} + +/** Every knob in the app, used to drive persistence generically. */ +val allTunables: List = + SportType.values().flatMap { tunableGroups(it) }.flatMap { it.items } diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Units.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Units.kt new file mode 100644 index 0000000..d6b4337 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/prefs/Units.kt @@ -0,0 +1,117 @@ +package com.zenvairo.sportssuitability.data.prefs + +import kotlin.math.abs +import kotlin.math.roundToInt + +/** + * Unit choices per measurement kind. Raw values from Open-Meteo are always kept in the + * canonical metric unit (km/h, metres, °C, cm) — these enums only affect display and input. + */ +enum class WindUnit(val label: String, val suffix: String) { + KMH("km/h", "km/h"), + KNOTS("nudos", "kt"), + MS("m/s", "m/s"), + MPH("mph", "mph") +} + +enum class WaveUnit(val label: String, val suffix: String) { + METERS("metros", "m"), + FEET("pies", "ft") +} + +enum class TempUnit(val label: String, val suffix: String) { + CELSIUS("Celsius", "°C"), + FAHRENHEIT("Fahrenheit", "°F") +} + +enum class SnowUnit(val label: String, val suffix: String) { + CM("centímetros", "cm"), + INCHES("pulgadas", "in") +} + +fun Double.kmhTo(unit: WindUnit): Double = when (unit) { + WindUnit.KMH -> this + WindUnit.KNOTS -> this * 0.539957 + WindUnit.MS -> this / 3.6 + WindUnit.MPH -> this * 0.621371 +} + +fun Double.toKmhFrom(unit: WindUnit): Double = when (unit) { + WindUnit.KMH -> this + WindUnit.KNOTS -> this / 0.539957 + WindUnit.MS -> this * 3.6 + WindUnit.MPH -> this / 0.621371 +} + +fun Double.metersTo(unit: WaveUnit): Double = when (unit) { + WaveUnit.METERS -> this + WaveUnit.FEET -> this * 3.28084 +} + +fun Double.toMetersFrom(unit: WaveUnit): Double = when (unit) { + WaveUnit.METERS -> this + WaveUnit.FEET -> this / 3.28084 +} + +fun Double.celsiusTo(unit: TempUnit): Double = when (unit) { + TempUnit.CELSIUS -> this + TempUnit.FAHRENHEIT -> this * 9.0 / 5.0 + 32.0 +} + +/** Converts an *absolute* temperature typed by the user back to °C. */ +fun Double.toCelsiusFrom(unit: TempUnit): Double = when (unit) { + TempUnit.CELSIUS -> this + TempUnit.FAHRENHEIT -> (this - 32.0) * 5.0 / 9.0 +} + +fun Double.cmTo(unit: SnowUnit): Double = when (unit) { + SnowUnit.CM -> this + SnowUnit.INCHES -> this / 2.54 +} + +fun Double.toCmFrom(unit: SnowUnit): Double = when (unit) { + SnowUnit.CM -> this + SnowUnit.INCHES -> this * 2.54 +} + +private fun Double.decimals(n: Int) = "%.${n}f".format(this) + +fun Double.formatWind(unit: WindUnit): String = "${kmhTo(unit).decimals(0)} ${unit.suffix}" +fun Double.formatWave(unit: WaveUnit): String = "${metersTo(unit).decimals(1)} ${unit.suffix}" +fun Double.formatTemp(unit: TempUnit): String = "${celsiusTo(unit).decimals(0)}${unit.suffix}" +fun Double.formatSnow(unit: SnowUnit): String = "${cmTo(unit).decimals(1)} ${unit.suffix}" +fun Double.formatSnowDepth(unit: SnowUnit): String = "${cmTo(unit).decimals(0)} ${unit.suffix}" + +fun Double.formatPeriod(): String = "${decimals(1)} s" +fun Double.formatMm(): String = "${decimals(1)} mm" +fun Double.formatPercent(): String = "${roundToInt()} %" +fun Double.formatHpa(): String = "${roundToInt()} hPa" +fun Double.formatAltitude(): String = "${roundToInt()} m" +fun Double.formatUv(): String = decimals(1) + +fun Double.formatVisibility(): String = + if (this >= 1000) "${(this / 1000).decimals(1)} km" else "${roundToInt()} m" + +fun Double.formatDuration(): String { + val totalMinutes = (this / 60).roundToInt() + return "${totalMinutes / 60} h ${totalMinutes % 60} min" +} + +private val COMPASS_ES = listOf( + "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", + "S", "SSO", "SO", "OSO", "O", "ONO", "NO", "NNO" +) + +/** Turns a bearing into a Spanish compass point, e.g. 225° → "SO". */ +fun Double.toCompass(): String { + val normalised = ((this % 360) + 360) % 360 + return COMPASS_ES[((normalised / 22.5).roundToInt()) % 16] +} + +fun Double.formatDirection(): String = "${toCompass()} (${roundToInt()}°)" + +/** Smallest angle between two bearings, always in 0..180. */ +fun angleDelta(a: Double, b: Double): Double { + val diff = abs(((a - b) % 360 + 360) % 360) + return if (diff > 180) 360 - diff else diff +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/remote/NetworkModule.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/remote/NetworkModule.kt new file mode 100644 index 0000000..c0e8668 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/remote/NetworkModule.kt @@ -0,0 +1,44 @@ +package com.zenvairo.sportssuitability.data.remote + +import kotlinx.serialization.json.Json +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Retrofit +import retrofit2.converter.kotlinx.serialization.asConverterFactory +import java.util.concurrent.TimeUnit + +/** No API key needed: Open-Meteo's free tier requires no authentication. */ +object NetworkModule { + + private val json = Json { + ignoreUnknownKeys = true + coerceInputValues = true + explicitNulls = false + } + + private val okHttpClient = OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .readTimeout(25, TimeUnit.SECONDS) + .retryOnConnectionFailure(true) + .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BASIC }) + .build() + + private fun retrofit(baseUrl: String): Retrofit = Retrofit.Builder() + .baseUrl(baseUrl) + .client(okHttpClient) + .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) + .build() + + val geocodingApi: GeocodingApi by lazy { + retrofit("https://geocoding-api.open-meteo.com/").create(GeocodingApi::class.java) + } + + val forecastApi: ForecastApi by lazy { + retrofit("https://api.open-meteo.com/").create(ForecastApi::class.java) + } + + val marineApi: MarineApi by lazy { + retrofit("https://marine-api.open-meteo.com/").create(MarineApi::class.java) + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/remote/OpenMeteoApi.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/remote/OpenMeteoApi.kt new file mode 100644 index 0000000..0733cfb --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/remote/OpenMeteoApi.kt @@ -0,0 +1,82 @@ +package com.zenvairo.sportssuitability.data.remote + +import retrofit2.http.GET +import retrofit2.http.Query + +/** Variable lists are centralised so the request and the parsing model stay in sync. */ +object OpenMeteoVars { + const val FORECAST_CURRENT = + "temperature_2m,apparent_temperature,relative_humidity_2m,precipitation,rain,showers," + + "snowfall,weather_code,cloud_cover,pressure_msl,surface_pressure," + + "wind_speed_10m,wind_gusts_10m,wind_direction_10m,is_day" + + const val FORECAST_HOURLY = + "temperature_2m,apparent_temperature,relative_humidity_2m,precipitation_probability," + + "precipitation,snowfall,snow_depth,weather_code,cloud_cover,visibility," + + "freezing_level_height,uv_index,wind_speed_10m,wind_gusts_10m,wind_direction_10m" + + const val FORECAST_DAILY = + "weather_code,temperature_2m_max,temperature_2m_min,apparent_temperature_max," + + "apparent_temperature_min,sunrise,sunset,daylight_duration,sunshine_duration," + + "uv_index_max,precipitation_sum,rain_sum,showers_sum,snowfall_sum,precipitation_hours," + + "precipitation_probability_max,wind_speed_10m_max,wind_gusts_10m_max," + + "wind_direction_10m_dominant" + + const val MARINE_CURRENT = + "wave_height,wave_period,wave_direction,wind_wave_height,wind_wave_period," + + "wind_wave_direction,swell_wave_height,swell_wave_period,swell_wave_peak_period," + + "swell_wave_direction,sea_surface_temperature,sea_level_height_msl," + + "ocean_current_velocity,ocean_current_direction" + + const val MARINE_HOURLY = + "wave_height,wave_period,wave_direction,swell_wave_height,swell_wave_period," + + "sea_surface_temperature,sea_level_height_msl" + + const val MARINE_DAILY = + "wave_height_max,wave_period_max,wave_direction_dominant,wind_wave_height_max," + + "wind_wave_period_max,swell_wave_height_max,swell_wave_period_max," + + "swell_wave_peak_period_max,swell_wave_direction_dominant" +} + +interface GeocodingApi { + @GET("v1/search") + suspend fun search( + @Query("name") name: String, + @Query("count") count: Int = 10, + @Query("language") language: String = "es", + @Query("format") format: String = "json" + ): GeocodingResponse +} + +/** + * `api.open-meteo.com` — atmosphere. One request returns "now", the hourly detail and the + * daily outlook, so a spot needs a single round trip instead of three. + */ +interface ForecastApi { + @GET("v1/forecast") + suspend fun bundle( + @Query("latitude") latitude: Double, + @Query("longitude") longitude: Double, + @Query("current") current: String = OpenMeteoVars.FORECAST_CURRENT, + @Query("hourly") hourly: String = OpenMeteoVars.FORECAST_HOURLY, + @Query("daily") daily: String = OpenMeteoVars.FORECAST_DAILY, + @Query("wind_speed_unit") windSpeedUnit: String = "kmh", + @Query("timezone") timezone: String = "auto", + @Query("forecast_days") forecastDays: Int = 8, + @Query("elevation") elevation: Double? = null + ): ForecastResponse +} + +/** `marine-api.open-meteo.com` — waves, swell, sea temperature and sea level (tides). */ +interface MarineApi { + @GET("v1/marine") + suspend fun bundle( + @Query("latitude") latitude: Double, + @Query("longitude") longitude: Double, + @Query("current") current: String = OpenMeteoVars.MARINE_CURRENT, + @Query("hourly") hourly: String = OpenMeteoVars.MARINE_HOURLY, + @Query("daily") daily: String = OpenMeteoVars.MARINE_DAILY, + @Query("timezone") timezone: String = "auto", + @Query("forecast_days") forecastDays: Int = 8 + ): MarineResponse +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/remote/OpenMeteoModels.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/remote/OpenMeteoModels.kt new file mode 100644 index 0000000..78180df --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/remote/OpenMeteoModels.kt @@ -0,0 +1,157 @@ +package com.zenvairo.sportssuitability.data.remote + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +data class GeocodingResponse( + val results: List? = null +) + +@Serializable +data class GeocodingResult( + val id: Long, + val name: String, + val latitude: Double, + val longitude: Double, + val elevation: Double? = null, + val country: String? = null, + val admin1: String? = null, + val admin2: String? = null +) { + val regionLabel: String? + get() = listOfNotNull(admin1, country).joinToString(", ").ifBlank { null } +} + +/** + * Response from `/v1/forecast`. Every field is nullable/defaulted so that a location + * missing a variable (or an Open-Meteo model that doesn't publish one) degrades to + * "no data" for that metric instead of failing the whole request. + */ +@Serializable +data class ForecastResponse( + val latitude: Double? = null, + val longitude: Double? = null, + val elevation: Double? = null, + val timezone: String? = null, + val current: CurrentForecast? = null, + val hourly: HourlyForecast? = null, + val daily: DailyForecast? = null +) + +@Serializable +data class CurrentForecast( + val time: String? = null, + @SerialName("temperature_2m") val temperature: Double? = null, + @SerialName("apparent_temperature") val apparentTemperature: Double? = null, + @SerialName("relative_humidity_2m") val humidity: Double? = null, + @SerialName("precipitation") val precipitation: Double? = null, + @SerialName("rain") val rain: Double? = null, + @SerialName("showers") val showers: Double? = null, + @SerialName("snowfall") val snowfall: Double? = null, + @SerialName("weather_code") val weatherCode: Int? = null, + @SerialName("cloud_cover") val cloudCover: Double? = null, + @SerialName("pressure_msl") val pressureMsl: Double? = null, + @SerialName("surface_pressure") val surfacePressure: Double? = null, + @SerialName("wind_speed_10m") val windSpeed: Double? = null, + @SerialName("wind_gusts_10m") val windGusts: Double? = null, + @SerialName("wind_direction_10m") val windDirection: Double? = null, + @SerialName("is_day") val isDay: Int? = null +) + +@Serializable +data class HourlyForecast( + val time: List = emptyList(), + @SerialName("temperature_2m") val temperature: List = emptyList(), + @SerialName("apparent_temperature") val apparentTemperature: List = emptyList(), + @SerialName("relative_humidity_2m") val humidity: List = emptyList(), + @SerialName("precipitation_probability") val precipitationProbability: List = emptyList(), + @SerialName("precipitation") val precipitation: List = emptyList(), + @SerialName("snowfall") val snowfall: List = emptyList(), + @SerialName("snow_depth") val snowDepth: List = emptyList(), + @SerialName("weather_code") val weatherCode: List = emptyList(), + @SerialName("cloud_cover") val cloudCover: List = emptyList(), + @SerialName("visibility") val visibility: List = emptyList(), + @SerialName("freezing_level_height") val freezingLevelHeight: List = emptyList(), + @SerialName("uv_index") val uvIndex: List = emptyList(), + @SerialName("wind_speed_10m") val windSpeed: List = emptyList(), + @SerialName("wind_gusts_10m") val windGusts: List = emptyList(), + @SerialName("wind_direction_10m") val windDirection: List = emptyList() +) + +@Serializable +data class DailyForecast( + val time: List = emptyList(), + @SerialName("weather_code") val weatherCode: List = emptyList(), + @SerialName("temperature_2m_max") val temperatureMax: List = emptyList(), + @SerialName("temperature_2m_min") val temperatureMin: List = emptyList(), + @SerialName("apparent_temperature_max") val apparentTemperatureMax: List = emptyList(), + @SerialName("apparent_temperature_min") val apparentTemperatureMin: List = emptyList(), + @SerialName("sunrise") val sunrise: List = emptyList(), + @SerialName("sunset") val sunset: List = emptyList(), + @SerialName("daylight_duration") val daylightDuration: List = emptyList(), + @SerialName("sunshine_duration") val sunshineDuration: List = emptyList(), + @SerialName("uv_index_max") val uvIndexMax: List = emptyList(), + @SerialName("precipitation_sum") val precipitationSum: List = emptyList(), + @SerialName("rain_sum") val rainSum: List = emptyList(), + @SerialName("showers_sum") val showersSum: List = emptyList(), + @SerialName("snowfall_sum") val snowfallSum: List = emptyList(), + @SerialName("precipitation_hours") val precipitationHours: List = emptyList(), + @SerialName("precipitation_probability_max") val precipitationProbabilityMax: List = emptyList(), + @SerialName("wind_speed_10m_max") val windSpeedMax: List = emptyList(), + @SerialName("wind_gusts_10m_max") val windGustsMax: List = emptyList(), + @SerialName("wind_direction_10m_dominant") val windDirectionDominant: List = emptyList() +) + +/** Response from `marine-api.open-meteo.com/v1/marine`. */ +@Serializable +data class MarineResponse( + val current: CurrentMarine? = null, + val hourly: HourlyMarine? = null, + val daily: DailyMarine? = null +) + +@Serializable +data class CurrentMarine( + val time: String? = null, + @SerialName("wave_height") val waveHeight: Double? = null, + @SerialName("wave_period") val wavePeriod: Double? = null, + @SerialName("wave_direction") val waveDirection: Double? = null, + @SerialName("wind_wave_height") val windWaveHeight: Double? = null, + @SerialName("wind_wave_period") val windWavePeriod: Double? = null, + @SerialName("wind_wave_direction") val windWaveDirection: Double? = null, + @SerialName("swell_wave_height") val swellWaveHeight: Double? = null, + @SerialName("swell_wave_period") val swellWavePeriod: Double? = null, + @SerialName("swell_wave_peak_period") val swellWavePeakPeriod: Double? = null, + @SerialName("swell_wave_direction") val swellWaveDirection: Double? = null, + @SerialName("sea_surface_temperature") val seaSurfaceTemperature: Double? = null, + @SerialName("sea_level_height_msl") val seaLevelHeightMsl: Double? = null, + @SerialName("ocean_current_velocity") val oceanCurrentVelocity: Double? = null, + @SerialName("ocean_current_direction") val oceanCurrentDirection: Double? = null +) + +@Serializable +data class HourlyMarine( + val time: List = emptyList(), + @SerialName("wave_height") val waveHeight: List = emptyList(), + @SerialName("wave_period") val wavePeriod: List = emptyList(), + @SerialName("wave_direction") val waveDirection: List = emptyList(), + @SerialName("swell_wave_height") val swellWaveHeight: List = emptyList(), + @SerialName("swell_wave_period") val swellWavePeriod: List = emptyList(), + @SerialName("sea_surface_temperature") val seaSurfaceTemperature: List = emptyList(), + @SerialName("sea_level_height_msl") val seaLevelHeightMsl: List = emptyList() +) + +@Serializable +data class DailyMarine( + val time: List = emptyList(), + @SerialName("wave_height_max") val waveHeightMax: List = emptyList(), + @SerialName("wave_period_max") val wavePeriodMax: List = emptyList(), + @SerialName("wave_direction_dominant") val waveDirectionDominant: List = emptyList(), + @SerialName("wind_wave_height_max") val windWaveHeightMax: List = emptyList(), + @SerialName("wind_wave_period_max") val windWavePeriodMax: List = emptyList(), + @SerialName("swell_wave_height_max") val swellWaveHeightMax: List = emptyList(), + @SerialName("swell_wave_period_max") val swellWavePeriodMax: List = emptyList(), + @SerialName("swell_wave_peak_period_max") val swellWavePeakPeriodMax: List = emptyList(), + @SerialName("swell_wave_direction_dominant") val swellWaveDirectionDominant: List = emptyList() +) diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/repository/Conditions.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/repository/Conditions.kt new file mode 100644 index 0000000..6be73f4 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/repository/Conditions.kt @@ -0,0 +1,141 @@ +package com.zenvairo.sportssuitability.data.repository + +import com.zenvairo.sportssuitability.data.local.Spot + +/** + * Everything the app knows about one spot right now and for the coming days. + * + * All values are kept in canonical metric units (km/h, m, °C, cm, mm, hPa) so the rules + * engine never has to convert; display units are applied only at the UI edge. + */ +data class SpotConditions( + val spot: Spot, + val now: NowConditions? = null, + val days: List = emptyList(), + val hours: List = emptyList(), + val fetchedAtEpochMs: Long = 0L, + /** Set when nothing could be fetched at all. */ + val error: String? = null, + /** Set when part of the data (e.g. the marine model) failed but the rest is usable. */ + val partialWarning: String? = null +) { + val today: DailyConditions? get() = days.firstOrNull() +} + +/** The "right now" snapshot. */ +data class NowConditions( + val time: String? = null, + // Atmosphere + val temperatureC: Double? = null, + val apparentTemperatureC: Double? = null, + val humidityPct: Double? = null, + val precipitationMm: Double? = null, + val rainMm: Double? = null, + val snowfallCm: Double? = null, + val snowDepthCm: Double? = null, + val weatherCode: Int? = null, + val cloudCoverPct: Double? = null, + val pressureHpa: Double? = null, + val windSpeedKmh: Double? = null, + val windGustsKmh: Double? = null, + val windDirectionDeg: Double? = null, + val freezingLevelM: Double? = null, + val visibilityM: Double? = null, + val uvIndex: Double? = null, + val isDay: Boolean? = null, + // Sea + val waveHeightM: Double? = null, + val wavePeriodS: Double? = null, + val waveDirectionDeg: Double? = null, + val windWaveHeightM: Double? = null, + val windWavePeriodS: Double? = null, + val windWaveDirectionDeg: Double? = null, + val swellHeightM: Double? = null, + val swellPeriodS: Double? = null, + val swellPeakPeriodS: Double? = null, + val swellDirectionDeg: Double? = null, + val seaTemperatureC: Double? = null, + val seaLevelM: Double? = null, + val currentVelocityKmh: Double? = null, + val currentDirectionDeg: Double? = null +) + +/** One day of the outlook. Wind/wave figures are daily maxima; precipitation is a daily sum. */ +data class DailyConditions( + val date: String, + val weatherCode: Int? = null, + val temperatureMaxC: Double? = null, + val temperatureMinC: Double? = null, + val apparentTemperatureMaxC: Double? = null, + val apparentTemperatureMinC: Double? = null, + val sunrise: String? = null, + val sunset: String? = null, + val daylightSeconds: Double? = null, + val sunshineSeconds: Double? = null, + val uvIndexMax: Double? = null, + val precipitationMm: Double? = null, + val rainMm: Double? = null, + val precipitationHours: Double? = null, + val precipitationProbabilityPct: Double? = null, + val snowfallCm: Double? = null, + /** Snow lying on the ground, taken as the day's maximum of the hourly series. */ + val snowDepthCm: Double? = null, + val windSpeedKmh: Double? = null, + val windGustsKmh: Double? = null, + val windDirectionDeg: Double? = null, + val freezingLevelM: Double? = null, + val visibilityM: Double? = null, + // Sea + val waveHeightM: Double? = null, + val wavePeriodS: Double? = null, + val waveDirectionDeg: Double? = null, + val windWaveHeightM: Double? = null, + val windWavePeriodS: Double? = null, + val swellHeightM: Double? = null, + val swellPeriodS: Double? = null, + val swellPeakPeriodS: Double? = null, + val swellDirectionDeg: Double? = null, + val seaTemperatureC: Double? = null, + val tideExtremes: List = emptyList() +) { + /** Mid-point temperature, handy for a one-glance figure. */ + val temperatureC: Double? + get() = when { + temperatureMaxC != null && temperatureMinC != null -> (temperatureMaxC + temperatureMinC) / 2 + else -> temperatureMaxC ?: temperatureMinC + } +} + +/** One hour of the outlook, used for the intraday "best window" strip. */ +data class HourlyConditions( + val time: String, + val temperatureC: Double? = null, + val apparentTemperatureC: Double? = null, + val humidityPct: Double? = null, + val precipitationMm: Double? = null, + val precipitationProbabilityPct: Double? = null, + val snowfallCm: Double? = null, + val snowDepthCm: Double? = null, + val weatherCode: Int? = null, + val cloudCoverPct: Double? = null, + val visibilityM: Double? = null, + val freezingLevelM: Double? = null, + val uvIndex: Double? = null, + val windSpeedKmh: Double? = null, + val windGustsKmh: Double? = null, + val windDirectionDeg: Double? = null, + val waveHeightM: Double? = null, + val wavePeriodS: Double? = null, + val waveDirectionDeg: Double? = null, + val swellHeightM: Double? = null, + val swellPeriodS: Double? = null, + val seaTemperatureC: Double? = null +) { + val date: String get() = time.substringBefore('T') + val hourLabel: String get() = time.substringAfter('T').take(5) +} + +/** A local high or low tide moment, derived from the hourly sea-level series. */ +data class TideExtreme(val time: String, val heightM: Double, val isHigh: Boolean) { + val hourLabel: String get() = time.substringAfter('T').take(5) +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/repository/SpotsRepository.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/repository/SpotsRepository.kt new file mode 100644 index 0000000..d124140 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/repository/SpotsRepository.kt @@ -0,0 +1,314 @@ +package com.zenvairo.sportssuitability.data.repository + +import com.zenvairo.sportssuitability.data.local.AppDatabase +import com.zenvairo.sportssuitability.data.local.Spot +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.remote.ForecastResponse +import com.zenvairo.sportssuitability.data.remote.GeocodingResult +import com.zenvairo.sportssuitability.data.remote.HourlyForecast +import com.zenvairo.sportssuitability.data.remote.HourlyMarine +import com.zenvairo.sportssuitability.data.remote.MarineResponse +import com.zenvairo.sportssuitability.data.remote.NetworkModule +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.Flow + +/** Snow depth arrives from Open-Meteo in metres; everything downstream works in centimetres. */ +private const val METRES_TO_CM = 100.0 + +class SpotsRepository(db: AppDatabase) { + + private val dao = db.spotDao() + + fun observeSpots(sportType: SportType): Flow> = dao.observeBySport(sportType) + + suspend fun allSpots(): List = dao.allSpots() + + suspend fun addSpot(result: GeocodingResult, sportType: SportType) { + dao.insert( + Spot( + name = result.name, + region = result.regionLabel, + latitude = result.latitude, + longitude = result.longitude, + sportType = sportType, + altitudeM = result.elevation.takeIf { sportType == SportType.SKI } + ) + ) + } + + suspend fun removeSpot(spot: Spot) = dao.delete(spot) + + suspend fun setAlertsEnabled(spot: Spot, enabled: Boolean) = dao.setAlertsEnabled(spot.id, enabled) + + suspend fun setCoastFacing(spot: Spot, facingDeg: Double?) = dao.setCoastFacing(spot.id, facingDeg) + + suspend fun setAltitude(spot: Spot, altitudeM: Double?) = dao.setAltitude(spot.id, altitudeM) + + suspend fun spotsWithAlerts(): List = dao.spotsWithAlerts() + + suspend fun searchLocations(query: String): List { + if (query.isBlank()) return emptyList() + return NetworkModule.geocodingApi.search(query).results.orEmpty() + } + + /** + * One network round trip per relevant API, in parallel. The atmosphere is fetched for + * every sport (wind matters to surfers too); the marine model is added for water sports. + * If only one of the two fails the spot still renders, with a warning attached. + */ + suspend fun fetchConditions(spot: Spot): SpotConditions = coroutineScope { + val needsMarine = spot.sportType == SportType.SURF || spot.sportType == SportType.WINDSURF + + val forecastJob = async { + runCatching { + NetworkModule.forecastApi.bundle( + latitude = spot.latitude, + longitude = spot.longitude, + elevation = spot.altitudeM.takeIf { spot.sportType == SportType.SKI } + ) + } + } + val marineJob = async { + if (!needsMarine) null + else runCatching { NetworkModule.marineApi.bundle(spot.latitude, spot.longitude) } + } + + val forecast = forecastJob.await() + val marine = marineJob.await() + + val forecastData = forecast.getOrNull() + val marineData = marine?.getOrNull() + + if (forecastData == null && marineData == null) { + val cause = forecast.exceptionOrNull() ?: marine?.exceptionOrNull() + return@coroutineScope SpotConditions( + spot = spot, + error = cause?.message ?: "No se pudieron obtener los datos", + fetchedAtEpochMs = System.currentTimeMillis() + ) + } + + val partial = when { + forecastData == null -> "Sin datos meteorológicos; solo se muestra el mar." + needsMarine && marineData == null -> "Sin datos del modelo marino; solo se muestra el tiempo." + else -> null + } + + SpotConditions( + spot = spot, + now = buildNow(forecastData, marineData), + days = buildDays(forecastData, marineData), + hours = buildHours(forecastData?.hourly, marineData?.hourly), + fetchedAtEpochMs = System.currentTimeMillis(), + partialWarning = partial + ) + } + + // ----------------------------------------------------------------------- + // Mapping + // ----------------------------------------------------------------------- + + private fun buildNow(forecast: ForecastResponse?, marine: MarineResponse?): NowConditions? { + val current = forecast?.current + val sea = marine?.current + if (current == null && sea == null) return null + + // These three only exist in the hourly series, so read them at the current hour. + val hourly = forecast?.hourly + val index = hourly?.let { nearestHourIndex(it.time, current?.time) } + + return NowConditions( + time = current?.time ?: sea?.time, + temperatureC = current?.temperature, + apparentTemperatureC = current?.apparentTemperature, + humidityPct = current?.humidity, + precipitationMm = current?.precipitation, + rainMm = current?.rain?.let { rain -> rain + (current.showers ?: 0.0) }, + snowfallCm = current?.snowfall, + snowDepthCm = index?.let { hourly.snowDepth.getOrNull(it) }?.times(METRES_TO_CM), + weatherCode = current?.weatherCode, + cloudCoverPct = current?.cloudCover, + pressureHpa = current?.pressureMsl ?: current?.surfacePressure, + windSpeedKmh = current?.windSpeed, + windGustsKmh = current?.windGusts, + windDirectionDeg = current?.windDirection, + freezingLevelM = index?.let { hourly.freezingLevelHeight.getOrNull(it) }, + visibilityM = index?.let { hourly.visibility.getOrNull(it) }, + uvIndex = index?.let { hourly.uvIndex.getOrNull(it) }, + isDay = current?.isDay?.let { it == 1 }, + waveHeightM = sea?.waveHeight, + wavePeriodS = sea?.wavePeriod, + waveDirectionDeg = sea?.waveDirection, + windWaveHeightM = sea?.windWaveHeight, + windWavePeriodS = sea?.windWavePeriod, + windWaveDirectionDeg = sea?.windWaveDirection, + swellHeightM = sea?.swellWaveHeight, + swellPeriodS = sea?.swellWavePeriod, + swellPeakPeriodS = sea?.swellWavePeakPeriod, + swellDirectionDeg = sea?.swellWaveDirection, + seaTemperatureC = sea?.seaSurfaceTemperature, + seaLevelM = sea?.seaLevelHeightMsl, + // Open-Meteo already reports ocean current velocity in km/h. + currentVelocityKmh = sea?.oceanCurrentVelocity, + currentDirectionDeg = sea?.oceanCurrentDirection + ) + } + + private fun buildDays(forecast: ForecastResponse?, marine: MarineResponse?): List { + val daily = forecast?.daily + val hourlyStats = hourlyDailyStats(forecast?.hourly) + val tidesByDate = extractTideExtremes(marine?.hourly).groupBy { it.time.substringBefore('T') } + val seaTempByDate = averageByDate( + marine?.hourly?.time.orEmpty(), + marine?.hourly?.seaSurfaceTemperature.orEmpty() + ) + + val marineDaily = marine?.daily + val marineIndexByDate = marineDaily?.time.orEmpty() + .withIndex().associate { (i, date) -> date to i } + + // The atmospheric series defines the calendar; ocean-only spots fall back to it. + val dates = daily?.time?.takeIf { it.isNotEmpty() } ?: marineDaily?.time.orEmpty() + + return dates.mapIndexed { i, date -> + val stats = hourlyStats[date] + val m = marineIndexByDate[date] + DailyConditions( + date = date, + weatherCode = daily?.weatherCode?.getOrNull(i), + temperatureMaxC = daily?.temperatureMax?.getOrNull(i), + temperatureMinC = daily?.temperatureMin?.getOrNull(i), + apparentTemperatureMaxC = daily?.apparentTemperatureMax?.getOrNull(i), + apparentTemperatureMinC = daily?.apparentTemperatureMin?.getOrNull(i), + sunrise = daily?.sunrise?.getOrNull(i), + sunset = daily?.sunset?.getOrNull(i), + daylightSeconds = daily?.daylightDuration?.getOrNull(i), + sunshineSeconds = daily?.sunshineDuration?.getOrNull(i), + uvIndexMax = daily?.uvIndexMax?.getOrNull(i), + precipitationMm = daily?.precipitationSum?.getOrNull(i), + rainMm = daily?.rainSum?.getOrNull(i)?.let { rain -> + rain + (daily.showersSum.getOrNull(i) ?: 0.0) + }, + precipitationHours = daily?.precipitationHours?.getOrNull(i), + precipitationProbabilityPct = daily?.precipitationProbabilityMax?.getOrNull(i), + snowfallCm = daily?.snowfallSum?.getOrNull(i), + snowDepthCm = stats?.maxSnowDepthCm, + windSpeedKmh = daily?.windSpeedMax?.getOrNull(i), + windGustsKmh = daily?.windGustsMax?.getOrNull(i), + windDirectionDeg = daily?.windDirectionDominant?.getOrNull(i), + freezingLevelM = stats?.meanFreezingLevelM, + visibilityM = stats?.minVisibilityM, + waveHeightM = m?.let { marineDaily?.waveHeightMax?.getOrNull(it) }, + wavePeriodS = m?.let { marineDaily?.wavePeriodMax?.getOrNull(it) }, + waveDirectionDeg = m?.let { marineDaily?.waveDirectionDominant?.getOrNull(it) }, + windWaveHeightM = m?.let { marineDaily?.windWaveHeightMax?.getOrNull(it) }, + windWavePeriodS = m?.let { marineDaily?.windWavePeriodMax?.getOrNull(it) }, + swellHeightM = m?.let { marineDaily?.swellWaveHeightMax?.getOrNull(it) }, + swellPeriodS = m?.let { marineDaily?.swellWavePeriodMax?.getOrNull(it) }, + swellPeakPeriodS = m?.let { marineDaily?.swellWavePeakPeriodMax?.getOrNull(it) }, + swellDirectionDeg = m?.let { marineDaily?.swellWaveDirectionDominant?.getOrNull(it) }, + seaTemperatureC = seaTempByDate[date], + tideExtremes = tidesByDate[date].orEmpty() + ) + } + } + + private fun buildHours(hourly: HourlyForecast?, marine: HourlyMarine?): List { + val marineIndexByTime = marine?.time.orEmpty() + .withIndex().associate { (i, time) -> time to i } + val times = hourly?.time?.takeIf { it.isNotEmpty() } ?: marine?.time.orEmpty() + + return times.mapIndexed { i, time -> + val m = marineIndexByTime[time] + HourlyConditions( + time = time, + temperatureC = hourly?.temperature?.getOrNull(i), + apparentTemperatureC = hourly?.apparentTemperature?.getOrNull(i), + humidityPct = hourly?.humidity?.getOrNull(i), + precipitationMm = hourly?.precipitation?.getOrNull(i), + precipitationProbabilityPct = hourly?.precipitationProbability?.getOrNull(i), + snowfallCm = hourly?.snowfall?.getOrNull(i), + snowDepthCm = hourly?.snowDepth?.getOrNull(i)?.times(METRES_TO_CM), + weatherCode = hourly?.weatherCode?.getOrNull(i), + cloudCoverPct = hourly?.cloudCover?.getOrNull(i), + visibilityM = hourly?.visibility?.getOrNull(i), + freezingLevelM = hourly?.freezingLevelHeight?.getOrNull(i), + uvIndex = hourly?.uvIndex?.getOrNull(i), + windSpeedKmh = hourly?.windSpeed?.getOrNull(i), + windGustsKmh = hourly?.windGusts?.getOrNull(i), + windDirectionDeg = hourly?.windDirection?.getOrNull(i), + waveHeightM = m?.let { marine?.waveHeight?.getOrNull(it) }, + wavePeriodS = m?.let { marine?.wavePeriod?.getOrNull(it) }, + waveDirectionDeg = m?.let { marine?.waveDirection?.getOrNull(it) }, + swellHeightM = m?.let { marine?.swellWaveHeight?.getOrNull(it) }, + swellPeriodS = m?.let { marine?.swellWavePeriod?.getOrNull(it) }, + seaTemperatureC = m?.let { marine?.seaSurfaceTemperature?.getOrNull(it) } + ) + } + } + + // ----------------------------------------------------------------------- + // Hourly → daily helpers + // ----------------------------------------------------------------------- + + private data class HourlyDayStats( + val maxSnowDepthCm: Double?, + val meanFreezingLevelM: Double?, + val minVisibilityM: Double? + ) + + /** Rolls up the variables Open-Meteo only publishes hourly into per-day figures. */ + private fun hourlyDailyStats(hourly: HourlyForecast?): Map { + if (hourly == null || hourly.time.isEmpty()) return emptyMap() + return hourly.time.indices + .groupBy { hourly.time[it].substringBefore('T') } + .mapValues { (_, indices) -> + HourlyDayStats( + maxSnowDepthCm = indices.mapNotNull { hourly.snowDepth.getOrNull(it) } + .maxOrNull()?.times(METRES_TO_CM), + meanFreezingLevelM = indices.mapNotNull { hourly.freezingLevelHeight.getOrNull(it) } + .takeIf { it.isNotEmpty() }?.average(), + minVisibilityM = indices.mapNotNull { hourly.visibility.getOrNull(it) }.minOrNull() + ) + } + } + + private fun averageByDate(times: List, values: List): Map = + times.indices + .groupBy { times[it].substringBefore('T') } + .mapNotNull { (date, indices) -> + indices.mapNotNull { values.getOrNull(it) } + .takeIf { it.isNotEmpty() }?.let { date to it.average() } + } + .toMap() + + /** Index of the hourly slot matching [target] (or the first slot when it can't be matched). */ + private fun nearestHourIndex(times: List, target: String?): Int? { + if (times.isEmpty()) return null + if (target == null) return 0 + val hourKey = target.take(13) // yyyy-MM-ddTHH + val exact = times.indexOfFirst { it.startsWith(hourKey) } + return if (exact >= 0) exact else 0 + } + + /** + * Local extrema of the hourly sea-level curve, which approximate the tide turns. + * Open-Meteo has no tide table on the free tier; sea level MSL is the closest stand-in. + */ + private fun extractTideExtremes(hourly: HourlyMarine?): List { + if (hourly == null || hourly.time.size < 3) return emptyList() + val extremes = mutableListOf() + for (i in 1 until hourly.time.size - 1) { + val prev = hourly.seaLevelHeightMsl.getOrNull(i - 1) ?: continue + val curr = hourly.seaLevelHeightMsl.getOrNull(i) ?: continue + val next = hourly.seaLevelHeightMsl.getOrNull(i + 1) ?: continue + val isPeak = curr > prev && curr >= next + val isTrough = curr < prev && curr <= next + if (isPeak || isTrough) { + extremes += TideExtreme(time = hourly.time[i], heightM = curr, isHigh = isPeak) + } + } + return extremes + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/repository/Suitability.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/repository/Suitability.kt new file mode 100644 index 0000000..a3e712d --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/repository/Suitability.kt @@ -0,0 +1,531 @@ +package com.zenvairo.sportssuitability.data.repository + +import com.zenvairo.sportssuitability.data.local.Spot +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.prefs.Limit +import com.zenvairo.sportssuitability.data.prefs.angleDelta +import com.zenvairo.sportssuitability.data.prefs.formatMm +import com.zenvairo.sportssuitability.data.prefs.formatSnow +import com.zenvairo.sportssuitability.data.prefs.formatSnowDepth +import com.zenvairo.sportssuitability.data.prefs.formatTemp +import com.zenvairo.sportssuitability.data.prefs.formatVisibility +import com.zenvairo.sportssuitability.data.prefs.formatWave +import com.zenvairo.sportssuitability.data.prefs.formatWind +import com.zenvairo.sportssuitability.data.prefs.toCompass +import kotlin.math.roundToInt + +/** Colours live in the UI layer ([com.zenvairo.sportssuitability.ui.color]) so the rules + * engine stays plain Kotlin and unit-testable. */ +enum class Suitability(val label: String) { + EXCELLENT("Ideal"), + GOOD("Bueno"), + FAIR("Regular"), + POOR("Flojo"), + NO_GO("No ir"), + UNKNOWN("Sin datos") +} + +/** + * The answer to "¿puedo ir?" for one spot on one day, with the reasoning attached so the + * card and the notification can both explain themselves. + */ +data class Verdict( + val suitability: Suitability, + /** 0–100, or `null` when there was not enough data to score anything. */ + val score: Int?, + val canGo: Boolean, + /** Hard limits that were crossed — each one on its own is enough to stay home. */ + val blockers: List = emptyList(), + /** Things that are poor but not disqualifying. */ + val warnings: List = emptyList(), + /** Things that are genuinely good today. */ + val highlights: List = emptyList() +) { + /** One line suitable for a notification or a card subtitle. */ + val headline: String + get() = when { + blockers.isNotEmpty() -> blockers.first() + highlights.isNotEmpty() -> highlights.joinToString(" · ") + warnings.isNotEmpty() -> warnings.first() + else -> suitability.label + } +} + +/** Where the wind blows relative to the coast — the difference between glass and slop. */ +enum class WindShore(val label: String) { + OFFSHORE("Viento offshore (de tierra)"), + CROSS("Viento cruzado"), + ONSHORE("Viento onshore (de mar)"), + UNKNOWN("Orientación no configurada") +} + +/** + * Sport-neutral snapshot the rules run against, so "now" and each forecast day are scored + * by exactly the same code. All values are canonical metric. + */ +data class RuleInput( + val windKmh: Double? = null, + val gustKmh: Double? = null, + val windDirectionDeg: Double? = null, + val waveHeightM: Double? = null, + val wavePeriodS: Double? = null, + val swellPeriodS: Double? = null, + val seaTempC: Double? = null, + val airTempC: Double? = null, + val precipitationMm: Double? = null, + val rainMm: Double? = null, + val snowfallCm: Double? = null, + val snowDepthCm: Double? = null, + val visibilityM: Double? = null, + val freezingLevelM: Double? = null, + val cloudCoverPct: Double? = null, + val coastFacingDeg: Double? = null +) + +fun NowConditions.toRuleInput(spot: Spot) = RuleInput( + windKmh = windSpeedKmh, + gustKmh = windGustsKmh, + windDirectionDeg = windDirectionDeg, + waveHeightM = waveHeightM, + wavePeriodS = wavePeriodS, + swellPeriodS = swellPeakPeriodS ?: swellPeriodS, + seaTempC = seaTemperatureC, + airTempC = temperatureC, + precipitationMm = precipitationMm, + rainMm = rainMm ?: precipitationMm, + snowfallCm = snowfallCm, + snowDepthCm = snowDepthCm, + visibilityM = visibilityM, + freezingLevelM = freezingLevelM, + cloudCoverPct = cloudCoverPct, + coastFacingDeg = spot.coastFacingDeg +) + +fun DailyConditions.toRuleInput(spot: Spot) = RuleInput( + windKmh = windSpeedKmh, + gustKmh = windGustsKmh, + windDirectionDeg = windDirectionDeg, + waveHeightM = waveHeightM, + wavePeriodS = wavePeriodS, + swellPeriodS = swellPeakPeriodS ?: swellPeriodS, + seaTempC = seaTemperatureC, + airTempC = temperatureMaxC ?: temperatureC, + precipitationMm = precipitationMm, + rainMm = rainMm ?: precipitationMm, + snowfallCm = snowfallCm, + snowDepthCm = snowDepthCm, + visibilityM = visibilityM, + freezingLevelM = freezingLevelM, + coastFacingDeg = spot.coastFacingDeg +) + +fun HourlyConditions.toRuleInput(spot: Spot) = RuleInput( + windKmh = windSpeedKmh, + gustKmh = windGustsKmh, + windDirectionDeg = windDirectionDeg, + waveHeightM = waveHeightM, + wavePeriodS = wavePeriodS, + swellPeriodS = swellPeriodS, + seaTempC = seaTemperatureC, + airTempC = temperatureC, + precipitationMm = precipitationMm, + rainMm = precipitationMm, + snowfallCm = snowfallCm, + snowDepthCm = snowDepthCm, + visibilityM = visibilityM, + freezingLevelM = freezingLevelM, + cloudCoverPct = cloudCoverPct, + coastFacingDeg = spot.coastFacingDeg +) + +fun windShore(windDirectionDeg: Double?, coastFacingDeg: Double?): WindShore { + if (windDirectionDeg == null || coastFacingDeg == null) return WindShore.UNKNOWN + // Meteorological direction is where the wind comes *from*; offshore wind therefore + // arrives from the bearing opposite the one the beach looks towards. + val delta = angleDelta(windDirectionDeg, (coastFacingDeg + 180.0) % 360.0) + return when { + delta <= 50 -> WindShore.OFFSHORE + delta >= 130 -> WindShore.ONSHORE + else -> WindShore.CROSS + } +} + +// --------------------------------------------------------------------------- +// Scoring primitives. Each returns 0.0 (useless) … 1.0 (perfect). +// --------------------------------------------------------------------------- + +/** Full marks inside [min, max], fading to zero over [tolerance] on either side. */ +private fun bandScore(value: Double, min: Double, max: Double, tolerance: Double): Double { + val lo = minOf(min, max) + val hi = maxOf(min, max) + val tol = tolerance.coerceAtLeast(0.001) + return when { + value in lo..hi -> 1.0 + value < lo -> (1.0 - (lo - value) / tol).coerceIn(0.0, 1.0) + else -> (1.0 - (value - hi) / tol).coerceIn(0.0, 1.0) + } +} + +/** Zero at or below [floor], full marks at or above [target]. */ +private fun atLeastScore(value: Double, floor: Double, target: Double): Double { + if (target <= floor) return if (value >= target) 1.0 else 0.0 + return ((value - floor) / (target - floor)).coerceIn(0.0, 1.0) +} + +/** Full marks at or below [target], zero at or above [ceiling]. */ +private fun atMostScore(value: Double, target: Double, ceiling: Double): Double { + if (ceiling <= target) return if (value <= target) 1.0 else 0.0 + return (1.0 - (value - target) / (ceiling - target)).coerceIn(0.0, 1.0) +} + +private data class Factor( + val label: String, + val weight: Double, + val score: Double, + val detail: String +) + +private class Evaluation { + val factors = mutableListOf() + val blockers = mutableListOf() + + fun factor(label: String, weight: Double, score: Double, detail: String) { + factors += Factor(label, weight, score.coerceIn(0.0, 1.0), detail) + } + + /** Records a blocker when [value] rises above an enabled [limit]. */ + fun blockIfAbove(limit: Limit, value: Double?, describe: (Double) -> String) { + if (limit.enabled && value != null && value > limit.value) blockers += describe(limit.value) + } + + /** Records a blocker when [value] falls below an enabled [limit]. */ + fun blockIfBelow(limit: Limit, value: Double?, describe: (Double) -> String) { + if (limit.enabled && value != null && value < limit.value) blockers += describe(limit.value) + } + + fun toVerdict(settings: AppSettings): Verdict { + val usable = factors.filter { it.weight > 0 } + val totalWeight = usable.sumOf { it.weight } + val score = if (totalWeight <= 0) null else + (usable.sumOf { it.score * it.weight } / totalWeight * 100).roundToInt() + + val warnings = usable.filter { it.score < 0.4 } + .sortedBy { it.score } + .map { "${it.label}: ${it.detail}" } + val highlights = usable.filter { it.score >= 0.85 && it.weight >= 1.0 } + .sortedByDescending { it.weight } + .take(3) + .map { "${it.label} ${it.detail}" } + + val suitability = when { + blockers.isNotEmpty() -> Suitability.NO_GO + score == null -> Suitability.UNKNOWN + score >= 85 -> Suitability.EXCELLENT + score >= 70 -> Suitability.GOOD + score >= settings.minScoreToGo -> Suitability.FAIR + else -> Suitability.POOR + } + + return Verdict( + suitability = suitability, + score = score, + canGo = blockers.isEmpty() && score != null && score >= settings.minScoreToGo, + blockers = blockers.toList(), + warnings = warnings.take(3), + highlights = highlights + ) + } +} + +// --------------------------------------------------------------------------- +// Per-sport rules +// --------------------------------------------------------------------------- + +private fun evaluateSurf(input: RuleInput, settings: AppSettings): Verdict { + val rules = settings.surf + val eval = Evaluation() + + eval.blockIfAbove(rules.waveHardMaxM, input.waveHeightM) { + "Ola demasiado grande: ${input.waveHeightM!!.formatWave(settings.waveUnit)} " + + "(límite ${it.formatWave(settings.waveUnit)})" + } + eval.blockIfBelow(rules.waveHardMinM, input.waveHeightM) { + "Sin ola: ${input.waveHeightM!!.formatWave(settings.waveUnit)} " + + "(mínimo ${it.formatWave(settings.waveUnit)})" + } + eval.blockIfBelow(rules.periodHardMinS, input.wavePeriodS) { + "Periodo demasiado corto: ${"%.1f".format(input.wavePeriodS)} s (mínimo ${"%.1f".format(it)} s)" + } + eval.blockIfAbove(rules.windHardMaxKmh, input.windKmh) { + "Demasiado viento: ${input.windKmh!!.formatWind(settings.windUnit)} " + + "(límite ${it.formatWind(settings.windUnit)})" + } + eval.blockIfBelow(rules.seaTempHardMinC, input.seaTempC) { + "Agua a ${input.seaTempC!!.formatTemp(settings.tempUnit)} " + + "(mínimo ${it.formatTemp(settings.tempUnit)})" + } + + input.waveHeightM?.let { wave -> + val span = (rules.waveIdealMaxM - rules.waveIdealMinM).coerceAtLeast(0.2) + eval.factor("Ola", 3.0, bandScore(wave, rules.waveIdealMinM, rules.waveIdealMaxM, span * 0.8), + wave.formatWave(settings.waveUnit)) + } + (input.swellPeriodS ?: input.wavePeriodS)?.let { period -> + eval.factor("Periodo", 2.0, + atLeastScore(period, rules.periodIdealMinS * 0.55, rules.periodIdealMinS), + "${"%.1f".format(period)} s") + } + input.windKmh?.let { wind -> + eval.factor("Viento", 2.0, + atMostScore(wind, rules.windIdealMaxKmh, rules.windIdealMaxKmh * 2.5 + 10), + wind.formatWind(settings.windUnit)) + } + if (rules.preferOffshore) { + val shore = windShore(input.windDirectionDeg, input.coastFacingDeg) + val score = when (shore) { + WindShore.OFFSHORE -> 1.0 + WindShore.CROSS -> 0.55 + WindShore.ONSHORE -> 0.15 + WindShore.UNKNOWN -> -1.0 + } + if (score >= 0) { + eval.factor("Dirección del viento", 1.5, score, + input.windDirectionDeg?.toCompass()?.let { "$it · ${shore.label}" } ?: shore.label) + } + } + input.seaTempC?.let { eval.factor("Agua", 0.5, atLeastScore(it, 8.0, 18.0), it.formatTemp(settings.tempUnit)) } + + return eval.toVerdict(settings) +} + +private fun evaluateWindsurf(input: RuleInput, settings: AppSettings): Verdict { + val rules = settings.windsurf + val eval = Evaluation() + val gustSpread = if (input.gustKmh != null && input.windKmh != null) + (input.gustKmh - input.windKmh).coerceAtLeast(0.0) else null + + eval.blockIfAbove(rules.windHardMaxKmh, input.windKmh) { + "Demasiado viento: ${input.windKmh!!.formatWind(settings.windUnit)} " + + "(límite ${it.formatWind(settings.windUnit)})" + } + eval.blockIfBelow(rules.windHardMinKmh, input.windKmh) { + "Sin viento: ${input.windKmh!!.formatWind(settings.windUnit)} " + + "(mínimo ${it.formatWind(settings.windUnit)})" + } + eval.blockIfAbove(rules.gustSpreadHardMaxKmh, gustSpread) { + "Viento muy racheado: +${gustSpread!!.formatWind(settings.windUnit)} de racha " + + "(límite ${it.formatWind(settings.windUnit)})" + } + eval.blockIfAbove(rules.waveHardMaxM, input.waveHeightM) { + "Mar demasiado formado: ${input.waveHeightM!!.formatWave(settings.waveUnit)} " + + "(límite ${it.formatWave(settings.waveUnit)})" + } + eval.blockIfBelow(rules.airTempHardMinC, input.airTempC) { + "Aire a ${input.airTempC!!.formatTemp(settings.tempUnit)} " + + "(mínimo ${it.formatTemp(settings.tempUnit)})" + } + eval.blockIfBelow(rules.seaTempHardMinC, input.seaTempC) { + "Agua a ${input.seaTempC!!.formatTemp(settings.tempUnit)} " + + "(mínimo ${it.formatTemp(settings.tempUnit)})" + } + + input.windKmh?.let { wind -> + val span = (rules.windIdealMaxKmh - rules.windIdealMinKmh).coerceAtLeast(5.0) + eval.factor("Viento", 4.0, + bandScore(wind, rules.windIdealMinKmh, rules.windIdealMaxKmh, span * 0.9), + wind.formatWind(settings.windUnit)) + } + gustSpread?.let { spread -> + val ceiling = if (rules.gustSpreadHardMaxKmh.enabled) rules.gustSpreadHardMaxKmh.value else 30.0 + eval.factor("Constancia", 1.5, atMostScore(spread, 8.0, ceiling), + "rachas +${spread.formatWind(settings.windUnit)}") + } + if (rules.preferSideShore) { + val shore = windShore(input.windDirectionDeg, input.coastFacingDeg) + val score = when (shore) { + WindShore.CROSS -> 1.0 + WindShore.ONSHORE -> 0.75 + WindShore.OFFSHORE -> 0.3 + WindShore.UNKNOWN -> -1.0 + } + if (score >= 0) { + eval.factor("Dirección del viento", 1.5, score, + input.windDirectionDeg?.toCompass()?.let { "$it · ${shore.label}" } ?: shore.label) + } + } + input.airTempC?.let { + eval.factor("Temperatura", 0.75, atLeastScore(it, 4.0, 18.0), it.formatTemp(settings.tempUnit)) + } + input.waveHeightM?.let { + val ceiling = if (rules.waveHardMaxM.enabled) rules.waveHardMaxM.value else 3.0 + eval.factor("Mar", 0.5, atMostScore(it, 1.2, ceiling), it.formatWave(settings.waveUnit)) + } + + return eval.toVerdict(settings) +} + +private fun evaluateSki(input: RuleInput, settings: AppSettings): Verdict { + val rules = settings.ski + val eval = Evaluation() + + eval.blockIfAbove(rules.windHardMaxKmh, input.windKmh) { + "Viento ${input.windKmh!!.formatWind(settings.windUnit)} " + + "(límite ${it.formatWind(settings.windUnit)}): remontes en riesgo de cierre" + } + eval.blockIfAbove(rules.gustHardMaxKmh, input.gustKmh) { + "Rachas de ${input.gustKmh!!.formatWind(settings.windUnit)} " + + "(límite ${it.formatWind(settings.windUnit)})" + } + eval.blockIfBelow(rules.snowDepthHardMinCm, input.snowDepthCm) { + "Espesor de ${input.snowDepthCm!!.formatSnowDepth(settings.snowUnit)} " + + "(mínimo ${it.formatSnowDepth(settings.snowUnit)})" + } + eval.blockIfAbove(rules.tempHardMaxC, input.airTempC) { + "Demasiado calor: ${input.airTempC!!.formatTemp(settings.tempUnit)} " + + "(límite ${it.formatTemp(settings.tempUnit)})" + } + eval.blockIfBelow(rules.tempHardMinC, input.airTempC) { + "Demasiado frío: ${input.airTempC!!.formatTemp(settings.tempUnit)} " + + "(mínimo ${it.formatTemp(settings.tempUnit)})" + } + eval.blockIfAbove(rules.rainHardMaxMm, input.rainMm) { + "Lluvia de ${input.rainMm!!.formatMm()} (límite ${it.formatMm()})" + } + eval.blockIfBelow(rules.visibilityHardMinM, input.visibilityM) { + "Visibilidad de ${input.visibilityM!!.formatVisibility()} (mínimo ${it.formatVisibility()})" + } + eval.blockIfAbove(rules.freezingLevelHardMaxM, input.freezingLevelM) { + "Cota de nieve a ${input.freezingLevelM!!.roundToInt()} m (límite ${it.roundToInt()} m)" + } + + input.snowDepthCm?.let { depth -> + val floor = if (rules.snowDepthHardMinCm.enabled) rules.snowDepthHardMinCm.value else 0.0 + eval.factor("Espesor", 3.0, + atLeastScore(depth, floor, rules.snowDepthRecommendedCm), + depth.formatSnowDepth(settings.snowUnit)) + } + input.snowfallCm?.let { fresh -> + // No fresh snow is not a disaster on a groomed piste, so this factor starts at 0.4. + val score = 0.4 + 0.6 * atLeastScore(fresh, 0.0, rules.freshSnowIdealCm) + eval.factor("Nieve fresca", 2.0, score, fresh.formatSnow(settings.snowUnit)) + } + input.windKmh?.let { wind -> + val ceiling = if (rules.windHardMaxKmh.enabled) rules.windHardMaxKmh.value + else rules.windIdealMaxKmh * 2.5 + eval.factor("Viento", 2.0, atMostScore(wind, rules.windIdealMaxKmh, ceiling), + wind.formatWind(settings.windUnit)) + } + input.airTempC?.let { temp -> + eval.factor("Temperatura", 1.5, + bandScore(temp, rules.tempIdealMinC, rules.tempIdealMaxC, 8.0), + temp.formatTemp(settings.tempUnit)) + } + input.rainMm?.let { rain -> + val ceiling = if (rules.rainHardMaxMm.enabled) rules.rainHardMaxMm.value else 10.0 + eval.factor("Lluvia", 1.5, atMostScore(rain, 0.4, ceiling), rain.formatMm()) + } + input.visibilityM?.let { vis -> + val floor = if (rules.visibilityHardMinM.enabled) rules.visibilityHardMinM.value else 200.0 + eval.factor("Visibilidad", 1.0, atLeastScore(vis, floor, 8000.0), vis.formatVisibility()) + } + input.cloudCoverPct?.let { cloud -> + eval.factor("Cielo", 0.5, atMostScore(cloud, 25.0, 100.0), "${cloud.roundToInt()} % nubes") + } + + return eval.toVerdict(settings) +} + +fun evaluate(sportType: SportType, input: RuleInput, settings: AppSettings): Verdict = + when (sportType) { + SportType.SURF -> evaluateSurf(input, settings) + SportType.WINDSURF -> evaluateWindsurf(input, settings) + SportType.SKI -> evaluateSki(input, settings) + } + +/** + * The input behind "¿puedo ir hoy?". + * + * Instantaneous readings (wind, waves, temperature, snowpack) come from the "now" snapshot, + * but rain and fresh snow are taken from today's totals: the thresholds are expressed per day + * — 8 mm of rain, 10 cm of fresh snow — and comparing them against a mm-per-hour reading + * would silently make every rule far too lenient. + */ +private fun SpotConditions.todayInput(): RuleInput? { + val fromNow = now?.toRuleInput(spot) + val fromToday = today?.toRuleInput(spot) + if (fromNow == null) return fromToday + if (fromToday == null) return fromNow + + return fromNow.copy( + windKmh = fromNow.windKmh ?: fromToday.windKmh, + gustKmh = fromNow.gustKmh ?: fromToday.gustKmh, + windDirectionDeg = fromNow.windDirectionDeg ?: fromToday.windDirectionDeg, + waveHeightM = fromNow.waveHeightM ?: fromToday.waveHeightM, + wavePeriodS = fromNow.wavePeriodS ?: fromToday.wavePeriodS, + swellPeriodS = fromNow.swellPeriodS ?: fromToday.swellPeriodS, + seaTempC = fromNow.seaTempC ?: fromToday.seaTempC, + airTempC = fromNow.airTempC ?: fromToday.airTempC, + snowDepthCm = fromNow.snowDepthCm ?: fromToday.snowDepthCm, + visibilityM = fromNow.visibilityM ?: fromToday.visibilityM, + freezingLevelM = fromNow.freezingLevelM ?: fromToday.freezingLevelM, + cloudCoverPct = fromNow.cloudCoverPct ?: fromToday.cloudCoverPct, + // Daily totals win for anything that accumulates. + precipitationMm = fromToday.precipitationMm ?: fromNow.precipitationMm, + rainMm = fromToday.rainMm ?: fromNow.rainMm, + snowfallCm = fromToday.snowfallCm ?: fromNow.snowfallCm + ) +} + +/** + * Verdict for today. Falls back to whichever of "now" and "today" is available, so a spot + * never shows "sin datos" just because one endpoint was quiet. + */ +fun SpotConditions.nowVerdict(settings: AppSettings): Verdict { + val input = todayInput() ?: return Verdict(Suitability.UNKNOWN, null, canGo = false) + return evaluate(spot.sportType, input, settings) +} + +fun SpotConditions.dailyVerdict(day: DailyConditions, settings: AppSettings): Verdict = + evaluate(spot.sportType, day.toRuleInput(spot), settings) + +/** + * Verdict for a single hour. Accumulating figures are taken from the hour's parent day for + * the same reason as [todayInput]: 10 cm of fresh snow is a daily figure, not an hourly one. + */ +fun SpotConditions.hourlyVerdict(hour: HourlyConditions, settings: AppSettings): Verdict { + val parentDay = days.firstOrNull { it.date == hour.date } + val input = hour.toRuleInput(spot).copy( + precipitationMm = parentDay?.precipitationMm ?: hour.precipitationMm, + rainMm = parentDay?.rainMm ?: hour.precipitationMm, + snowfallCm = parentDay?.snowfallCm ?: hour.snowfallCm + ) + return evaluate(spot.sportType, input, settings) +} + +/** + * Longest unbroken run of go-able hours on [date] — the window worth aiming for. + * Returns the first and last hour labels, or null when no hour makes the cut. + */ +fun SpotConditions.bestWindow(date: String, settings: AppSettings): Pair? { + val onDate = hours.filter { it.date == date } + if (onDate.isEmpty()) return null + + var bestStart = -1 + var bestLength = 0 + var runStart = -1 + onDate.forEachIndexed { index, hour -> + if (hourlyVerdict(hour, settings).canGo) { + if (runStart < 0) runStart = index + val length = index - runStart + 1 + if (length > bestLength) { + bestLength = length + bestStart = runStart + } + } else { + runStart = -1 + } + } + if (bestLength == 0) return null + return onDate[bestStart].hourLabel to onDate[bestStart + bestLength - 1].hourLabel +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/data/repository/WeatherCode.kt b/app/src/main/java/com/zenvairo/sportssuitability/data/repository/WeatherCode.kt new file mode 100644 index 0000000..9398f33 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/data/repository/WeatherCode.kt @@ -0,0 +1,49 @@ +package com.zenvairo.sportssuitability.data.repository + +/** WMO weather interpretation codes as published by Open-Meteo, in Spanish. */ +fun weatherCodeText(code: Int?): String? = when (code) { + null -> null + 0 -> "Despejado" + 1 -> "Mayormente despejado" + 2 -> "Parcialmente nublado" + 3 -> "Nublado" + 45 -> "Niebla" + 48 -> "Niebla helada" + 51 -> "Llovizna débil" + 53 -> "Llovizna moderada" + 55 -> "Llovizna intensa" + 56 -> "Llovizna helada débil" + 57 -> "Llovizna helada intensa" + 61 -> "Lluvia débil" + 63 -> "Lluvia moderada" + 65 -> "Lluvia fuerte" + 66 -> "Lluvia helada débil" + 67 -> "Lluvia helada fuerte" + 71 -> "Nevada débil" + 73 -> "Nevada moderada" + 75 -> "Nevada fuerte" + 77 -> "Cinarra" + 80 -> "Chubascos débiles" + 81 -> "Chubascos moderados" + 82 -> "Chubascos torrenciales" + 85 -> "Chubascos de nieve débiles" + 86 -> "Chubascos de nieve fuertes" + 95 -> "Tormenta" + 96 -> "Tormenta con granizo" + 99 -> "Tormenta con granizo fuerte" + else -> "Código $code" +} + +/** A compact emoji for the code, used in the day strip and notifications. */ +fun weatherCodeEmoji(code: Int?, isDay: Boolean = true): String = when (code) { + null -> "•" + 0 -> if (isDay) "☀️" else "🌙" + 1, 2 -> if (isDay) "🌤️" else "☁️" + 3 -> "☁️" + 45, 48 -> "🌫️" + 51, 53, 55, 56, 57 -> "🌦️" + 61, 63, 65, 66, 67, 80, 81, 82 -> "🌧️" + 71, 73, 75, 77, 85, 86 -> "❄️" + 95, 96, 99 -> "⛈️" + else -> "•" +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/Metrics.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/Metrics.kt new file mode 100644 index 0000000..887b0b1 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/Metrics.kt @@ -0,0 +1,220 @@ +package com.zenvairo.sportssuitability.ui + +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.prefs.formatAltitude +import com.zenvairo.sportssuitability.data.prefs.formatDirection +import com.zenvairo.sportssuitability.data.prefs.formatDuration +import com.zenvairo.sportssuitability.data.prefs.formatHpa +import com.zenvairo.sportssuitability.data.prefs.formatMm +import com.zenvairo.sportssuitability.data.prefs.formatPercent +import com.zenvairo.sportssuitability.data.prefs.formatPeriod +import com.zenvairo.sportssuitability.data.prefs.formatSnow +import com.zenvairo.sportssuitability.data.prefs.formatSnowDepth +import com.zenvairo.sportssuitability.data.prefs.formatTemp +import com.zenvairo.sportssuitability.data.prefs.formatUv +import com.zenvairo.sportssuitability.data.prefs.formatVisibility +import com.zenvairo.sportssuitability.data.prefs.formatWave +import com.zenvairo.sportssuitability.data.prefs.formatWind +import com.zenvairo.sportssuitability.data.repository.DailyConditions +import com.zenvairo.sportssuitability.data.repository.SpotConditions +import com.zenvairo.sportssuitability.data.repository.weatherCodeText +import com.zenvairo.sportssuitability.data.repository.windShore +import com.zenvairo.sportssuitability.data.repository.WindShore + +/** One labelled reading, ready to be rendered as a chip. */ +data class Metric(val label: String, val value: String) + +data class MetricSection(val title: String, val metrics: List) + +private fun sectionOf(title: String, vararg metrics: Metric?): MetricSection? { + val present = metrics.filterNotNull() + return if (present.isEmpty()) null else MetricSection(title, present) +} + +private fun metric(label: String, value: String?): Metric? = + value?.let { Metric(label, it) } + +/** + * Every reading the app has for "right now", grouped so the section that matters most to + * the sport comes first. Missing readings simply disappear rather than showing blanks. + */ +fun SpotConditions.nowSections(settings: AppSettings): List { + val now = now ?: return emptyList() + val day = today + + val sea = sectionOf( + "Mar", + metric("Altura de ola", now.waveHeightM?.formatWave(settings.waveUnit)), + metric("Periodo", now.wavePeriodS?.formatPeriod()), + metric("Dirección de la ola", now.waveDirectionDeg?.formatDirection()), + metric("Mar de fondo", now.swellHeightM?.formatWave(settings.waveUnit)), + metric("Periodo del fondo", (now.swellPeakPeriodS ?: now.swellPeriodS)?.formatPeriod()), + metric("Dirección del fondo", now.swellDirectionDeg?.formatDirection()), + metric("Mar de viento", now.windWaveHeightM?.formatWave(settings.waveUnit)), + metric("Periodo del mar de viento", now.windWavePeriodS?.formatPeriod()), + metric("Temperatura del agua", now.seaTemperatureC?.formatTemp(settings.tempUnit)), + metric("Corriente", now.currentVelocityKmh?.formatWind(settings.windUnit)), + metric("Dirección de la corriente", now.currentDirectionDeg?.formatDirection()), + metric("Nivel del mar", now.seaLevelM?.let { "%.2f m".format(it) }) + ) + + val shore = windShore(now.windDirectionDeg, spot.coastFacingDeg) + val wind = sectionOf( + "Viento", + metric("Viento", now.windSpeedKmh?.formatWind(settings.windUnit)), + metric("Rachas", now.windGustsKmh?.formatWind(settings.windUnit)), + metric("Dirección", now.windDirectionDeg?.formatDirection()), + metric("Respecto a la costa", shore.label.takeIf { shore != WindShore.UNKNOWN }) + ) + + val snow = sectionOf( + "Nieve", + metric("Espesor", now.snowDepthCm?.formatSnowDepth(settings.snowUnit)), + metric("Nieve fresca (ahora)", now.snowfallCm?.formatSnow(settings.snowUnit)), + metric("Nieve fresca (hoy)", day?.snowfallCm?.formatSnow(settings.snowUnit)), + metric("Cota de nieve", now.freezingLevelM?.formatAltitude()), + metric("Altitud del punto", spot.altitudeM?.formatAltitude()) + ) + + val air = sectionOf( + "Aire", + metric("Cielo", weatherCodeText(now.weatherCode)), + metric("Temperatura", now.temperatureC?.formatTemp(settings.tempUnit)), + metric("Sensación térmica", now.apparentTemperatureC?.formatTemp(settings.tempUnit)), + metric("Humedad", now.humidityPct?.formatPercent()), + metric("Nubosidad", now.cloudCoverPct?.formatPercent()), + metric("Precipitación", now.precipitationMm?.formatMm()), + metric("Presión", now.pressureHpa?.formatHpa()), + metric("Visibilidad", now.visibilityM?.formatVisibility()), + metric("Índice UV", now.uvIndex?.formatUv()) + ) + + val sun = sectionOf( + "Sol", + metric("Amanecer", day?.sunrise?.substringAfter('T')?.take(5)), + metric("Atardecer", day?.sunset?.substringAfter('T')?.take(5)), + metric("Horas de luz", day?.daylightSeconds?.formatDuration()), + metric("Horas de sol", day?.sunshineSeconds?.formatDuration()), + metric("UV máximo hoy", day?.uvIndexMax?.formatUv()) + ) + + val tides = day?.tideExtremes + ?.takeIf { it.isNotEmpty() } + ?.let { extremes -> + MetricSection( + "Mareas de hoy", + extremes.map { + Metric( + if (it.isHigh) "Pleamar ${it.hourLabel}" else "Bajamar ${it.hourLabel}", + "%.2f m".format(it.heightM) + ) + } + ) + } + + val ordered = when (spot.sportType) { + SportType.SURF -> listOf(sea, wind, tides, air, sun) + SportType.WINDSURF -> listOf(wind, sea, air, tides, sun) + SportType.SKI -> listOf(snow, wind, air, sun) + } + return ordered.filterNotNull() +} + +/** The same treatment for one forecast day. */ +fun SpotConditions.daySections(day: DailyConditions, settings: AppSettings): List { + val sea = sectionOf( + "Mar", + metric("Ola máxima", day.waveHeightM?.formatWave(settings.waveUnit)), + metric("Periodo máximo", day.wavePeriodS?.formatPeriod()), + metric("Dirección dominante", day.waveDirectionDeg?.formatDirection()), + metric("Mar de fondo", day.swellHeightM?.formatWave(settings.waveUnit)), + metric("Periodo del fondo", (day.swellPeakPeriodS ?: day.swellPeriodS)?.formatPeriod()), + metric("Dirección del fondo", day.swellDirectionDeg?.formatDirection()), + metric("Mar de viento", day.windWaveHeightM?.formatWave(settings.waveUnit)), + metric("Temperatura del agua", day.seaTemperatureC?.formatTemp(settings.tempUnit)) + ) + + val shore = windShore(day.windDirectionDeg, spot.coastFacingDeg) + val wind = sectionOf( + "Viento", + metric("Viento máximo", day.windSpeedKmh?.formatWind(settings.windUnit)), + metric("Rachas máximas", day.windGustsKmh?.formatWind(settings.windUnit)), + metric("Dirección dominante", day.windDirectionDeg?.formatDirection()), + metric("Respecto a la costa", shore.label.takeIf { shore != WindShore.UNKNOWN }) + ) + + val snow = sectionOf( + "Nieve", + metric("Espesor máximo", day.snowDepthCm?.formatSnowDepth(settings.snowUnit)), + metric("Nieve fresca", day.snowfallCm?.formatSnow(settings.snowUnit)), + metric("Cota de nieve media", day.freezingLevelM?.formatAltitude()) + ) + + val air = sectionOf( + "Aire", + metric("Cielo", weatherCodeText(day.weatherCode)), + metric("Máxima", day.temperatureMaxC?.formatTemp(settings.tempUnit)), + metric("Mínima", day.temperatureMinC?.formatTemp(settings.tempUnit)), + metric("Sensación máxima", day.apparentTemperatureMaxC?.formatTemp(settings.tempUnit)), + metric("Sensación mínima", day.apparentTemperatureMinC?.formatTemp(settings.tempUnit)), + metric("Precipitación", day.precipitationMm?.formatMm()), + metric("Probabilidad de lluvia", day.precipitationProbabilityPct?.formatPercent()), + metric("Horas de precipitación", day.precipitationHours?.let { "${it.toInt()} h" }), + metric("Visibilidad mínima", day.visibilityM?.formatVisibility()) + ) + + val sun = sectionOf( + "Sol", + metric("Amanecer", day.sunrise?.substringAfter('T')?.take(5)), + metric("Atardecer", day.sunset?.substringAfter('T')?.take(5)), + metric("Horas de luz", day.daylightSeconds?.formatDuration()), + metric("Horas de sol", day.sunshineSeconds?.formatDuration()), + metric("UV máximo", day.uvIndexMax?.formatUv()) + ) + + val tides = day.tideExtremes.takeIf { it.isNotEmpty() }?.let { extremes -> + MetricSection( + "Mareas", + extremes.map { + Metric( + if (it.isHigh) "Pleamar ${it.hourLabel}" else "Bajamar ${it.hourLabel}", + "%.2f m".format(it.heightM) + ) + } + ) + } + + val ordered = when (spot.sportType) { + SportType.SURF -> listOf(sea, wind, tides, air, sun) + SportType.WINDSURF -> listOf(wind, sea, air, tides, sun) + SportType.SKI -> listOf(snow, wind, air, sun) + } + return ordered.filterNotNull() +} + +/** The three or four readings that belong on the collapsed card, chosen per sport. */ +fun SpotConditions.headlineMetrics(settings: AppSettings): List { + val now = now ?: return emptyList() + val day = today + return when (spot.sportType) { + SportType.SURF -> listOfNotNull( + metric("Ola", now.waveHeightM?.formatWave(settings.waveUnit)), + metric("Periodo", (now.swellPeakPeriodS ?: now.wavePeriodS)?.formatPeriod()), + metric("Viento", now.windSpeedKmh?.formatWind(settings.windUnit)), + metric("Agua", now.seaTemperatureC?.formatTemp(settings.tempUnit)) + ) + SportType.WINDSURF -> listOfNotNull( + metric("Viento", now.windSpeedKmh?.formatWind(settings.windUnit)), + metric("Rachas", now.windGustsKmh?.formatWind(settings.windUnit)), + metric("Dirección", now.windDirectionDeg?.formatDirection()), + metric("Ola", now.waveHeightM?.formatWave(settings.waveUnit)) + ) + SportType.SKI -> listOfNotNull( + metric("Espesor", now.snowDepthCm?.formatSnowDepth(settings.snowUnit)), + metric("Fresca hoy", day?.snowfallCm?.formatSnow(settings.snowUnit)), + metric("Viento", now.windSpeedKmh?.formatWind(settings.windUnit)), + metric("Temperatura", now.temperatureC?.formatTemp(settings.tempUnit)) + ) + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/SportUiInfo.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/SportUiInfo.kt new file mode 100644 index 0000000..12c3b55 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/SportUiInfo.kt @@ -0,0 +1,16 @@ +package com.zenvairo.sportssuitability.ui + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AcUnit +import androidx.compose.material.icons.filled.Air +import androidx.compose.material.icons.filled.Waves +import androidx.compose.ui.graphics.vector.ImageVector +import com.zenvairo.sportssuitability.data.local.SportType + +data class SportUiInfo(val label: String, val icon: ImageVector) + +fun SportType.uiInfo(): SportUiInfo = when (this) { + SportType.SURF -> SportUiInfo("Surf", Icons.Filled.Waves) + SportType.WINDSURF -> SportUiInfo("Windsurf", Icons.Filled.Air) + SportType.SKI -> SportUiInfo("Esquí", Icons.Filled.AcUnit) +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/SpotsViewModel.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/SpotsViewModel.kt new file mode 100644 index 0000000..31064be --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/SpotsViewModel.kt @@ -0,0 +1,188 @@ +package com.zenvairo.sportssuitability.ui + +import android.content.Context +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import com.zenvairo.sportssuitability.alerts.AlertScheduler +import com.zenvairo.sportssuitability.alerts.DailyAlertWorker +import com.zenvairo.sportssuitability.alerts.WeeklyForecastWorker +import com.zenvairo.sportssuitability.data.local.Spot +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.prefs.SettingsRepository +import com.zenvairo.sportssuitability.data.remote.GeocodingResult +import com.zenvairo.sportssuitability.data.repository.SpotConditions +import com.zenvairo.sportssuitability.data.repository.SpotsRepository +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch + +private const val SEARCH_DEBOUNCE_MS = 350L +private const val MIN_SEARCH_LENGTH = 2 + +data class SportUiState( + val conditions: List = emptyList(), + val isLoading: Boolean = false, + val isRefreshing: Boolean = false +) + +data class SearchUiState( + val query: String = "", + val results: List = emptyList(), + val isSearching: Boolean = false, + val error: String? = null +) + +class SpotsViewModel( + private val repository: SpotsRepository, + private val settingsRepository: SettingsRepository, + private val appContext: Context +) : ViewModel() { + + private val _uiStateBySport = MutableStateFlow( + SportType.values().associateWith { SportUiState() } + ) + val uiStateBySport: StateFlow> = _uiStateBySport.asStateFlow() + + private val _search = MutableStateFlow(SearchUiState()) + val search: StateFlow = _search.asStateFlow() + + val settings: StateFlow = settingsRepository.settings.stateIn( + viewModelScope, SharingStarted.Eagerly, AppSettings() + ) + + private var searchJob: Job? = null + + init { + SportType.values().forEach { observeSport(it) } + } + + private fun observeSport(sport: SportType) { + viewModelScope.launch { + repository.observeSpots(sport).collect { spots -> + _uiStateBySport.update(sport) { it.copy(isLoading = spots.isNotEmpty()) } + val results = fetchAll(spots) + _uiStateBySport.update(sport) { + it.copy(conditions = results, isLoading = false, isRefreshing = false) + } + } + } + } + + fun refreshSport(sport: SportType) { + viewModelScope.launch { + val spots = _uiStateBySport.value[sport]?.conditions.orEmpty().map { it.spot } + if (spots.isEmpty()) return@launch + _uiStateBySport.update(sport) { it.copy(isRefreshing = true) } + val refreshed = fetchAll(spots) + _uiStateBySport.update(sport) { it.copy(conditions = refreshed, isRefreshing = false) } + } + } + + private suspend fun fetchAll(spots: List): List = coroutineScope { + spots.map { spot -> async { repository.fetchConditions(spot) } }.awaitAll() + } + + // -- Settings ---------------------------------------------------------- + + fun updateSettings(transform: (AppSettings) -> AppSettings) { + viewModelScope.launch { + // Re-arm from the value update() just wrote: the settings StateFlow may not have + // caught up with DataStore yet, and a stale read would schedule the old hour. + val stored = settingsRepository.update(transform) + AlertScheduler.rescheduleAll(appContext, stored.alerts) + } + } + + fun resetSportDefaults(sport: SportType) { + viewModelScope.launch { settingsRepository.resetSportDefaults(sport) } + } + + /** Fires an alert immediately so the user can see what it will look like. */ + fun sendTestDailyAlert() { + WorkManager.getInstance(appContext) + .enqueue(OneTimeWorkRequestBuilder().build()) + } + + fun sendTestWeeklyAlert() { + WorkManager.getInstance(appContext) + .enqueue(OneTimeWorkRequestBuilder().build()) + } + + // -- Location search --------------------------------------------------- + + fun onSearchQueryChanged(query: String) { + _search.value = _search.value.copy(query = query, error = null) + searchJob?.cancel() + if (query.trim().length < MIN_SEARCH_LENGTH) { + _search.value = _search.value.copy(results = emptyList(), isSearching = false) + return + } + searchJob = viewModelScope.launch { + delay(SEARCH_DEBOUNCE_MS) + searchNow() + } + } + + fun searchLocations() { + searchJob?.cancel() + searchJob = viewModelScope.launch { searchNow() } + } + + private suspend fun searchNow() { + val query = _search.value.query.trim() + if (query.isEmpty()) return + _search.value = _search.value.copy(isSearching = true, error = null) + val outcome = runCatching { repository.searchLocations(query) } + _search.value = _search.value.copy( + results = outcome.getOrDefault(emptyList()), + isSearching = false, + error = outcome.exceptionOrNull()?.let { "No se pudo buscar: ${it.message}" } + ) + } + + fun clearSearch() { + searchJob?.cancel() + _search.value = SearchUiState() + } + + // -- Spot mutations ---------------------------------------------------- + + fun addSpot(result: GeocodingResult, sportType: SportType) { + viewModelScope.launch { repository.addSpot(result, sportType) } + } + + fun removeSpot(spot: Spot) { + viewModelScope.launch { repository.removeSpot(spot) } + } + + fun toggleAlerts(spot: Spot, enabled: Boolean) { + viewModelScope.launch { repository.setAlertsEnabled(spot, enabled) } + } + + // Room re-emits the spot list after each write, so the observer refetches on its own. + fun setCoastFacing(spot: Spot, facingDeg: Double?) { + viewModelScope.launch { repository.setCoastFacing(spot, facingDeg) } + } + + fun setAltitude(spot: Spot, altitudeM: Double?) { + viewModelScope.launch { repository.setAltitude(spot, altitudeM) } + } + + private fun MutableStateFlow>.update( + sport: SportType, + transform: (SportUiState) -> SportUiState + ) { + value = value.toMutableMap().apply { this[sport] = transform(this[sport] ?: SportUiState()) } + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/SpotsViewModelFactory.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/SpotsViewModelFactory.kt new file mode 100644 index 0000000..caebfa8 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/SpotsViewModelFactory.kt @@ -0,0 +1,18 @@ +package com.zenvairo.sportssuitability.ui + +import android.content.Context +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import com.zenvairo.sportssuitability.data.prefs.SettingsRepository +import com.zenvairo.sportssuitability.data.repository.SpotsRepository + +class SpotsViewModelFactory( + private val repository: SpotsRepository, + private val settingsRepository: SettingsRepository, + private val appContext: Context +) : ViewModelProvider.Factory { + override fun create(modelClass: Class): T { + @Suppress("UNCHECKED_CAST") + return SpotsViewModel(repository, settingsRepository, appContext) as T + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/SuitabilityUi.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/SuitabilityUi.kt new file mode 100644 index 0000000..6711ee2 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/SuitabilityUi.kt @@ -0,0 +1,15 @@ +package com.zenvairo.sportssuitability.ui + +import androidx.compose.ui.graphics.Color +import com.zenvairo.sportssuitability.data.repository.Suitability + +/** Traffic-light colours for each verdict, kept out of the rules engine. */ +val Suitability.color: Color + get() = when (this) { + Suitability.EXCELLENT -> Color(0xFF1B7F3B) + Suitability.GOOD -> Color(0xFF5FA531) + Suitability.FAIR -> Color(0xFFE0A100) + Suitability.POOR -> Color(0xFFD2622B) + Suitability.NO_GO -> Color(0xFFB3261E) + Suitability.UNKNOWN -> Color(0xFF8A8A8A) + } diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/components/AddSpotDialog.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/AddSpotDialog.kt new file mode 100644 index 0000000..4846175 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/AddSpotDialog.kt @@ -0,0 +1,75 @@ +package com.zenvairo.sportssuitability.ui.components + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.zenvairo.sportssuitability.data.prefs.formatAltitude +import com.zenvairo.sportssuitability.data.remote.GeocodingResult +import com.zenvairo.sportssuitability.ui.SearchUiState + +@Composable +fun AddSpotDialog( + sportLabel: String, + state: SearchUiState, + onQueryChanged: (String) -> Unit, + onSearch: () -> Unit, + onPick: (GeocodingResult) -> Unit, + onDismiss: () -> Unit +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Añadir sitio de $sportLabel") }, + text = { + Column { + OutlinedTextField( + value = state.query, + onValueChange = onQueryChanged, + label = { Text("Nombre del lugar") }, + supportingText = { Text("Escribe y espera; la búsqueda es automática") }, + modifier = Modifier.fillMaxWidth(), + singleLine = true + ) + state.error?.let { + Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) + } + if (state.isSearching) { + CircularProgressIndicator(modifier = Modifier.padding(16.dp)) + } else { + LazyColumn(modifier = Modifier.height(280.dp)) { + items(state.results, key = { it.id }) { result -> + ListItem( + headlineContent = { Text(result.name) }, + supportingContent = { + val details = listOfNotNull( + result.regionLabel, + result.elevation?.formatAltitude() + ).joinToString(" · ") + if (details.isNotBlank()) Text(details) + }, + modifier = Modifier + .fillMaxWidth() + .clickable { onPick(result) } + ) + } + } + } + } + }, + confirmButton = { TextButton(onClick = onSearch) { Text("Buscar") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancelar") } } + ) +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/components/Common.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/Common.kt new file mode 100644 index 0000000..d6e52d4 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/Common.kt @@ -0,0 +1,135 @@ +package com.zenvairo.sportssuitability.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.zenvairo.sportssuitability.data.repository.Suitability +import com.zenvairo.sportssuitability.ui.Metric +import com.zenvairo.sportssuitability.ui.MetricSection +import com.zenvairo.sportssuitability.ui.color + +/** The coloured "Ideal / No ir" pill, optionally carrying the 0–100 score. */ +@Composable +fun SuitabilityBadge(suitability: Suitability, score: Int? = null) { + Row( + modifier = Modifier + .clip(RoundedCornerShape(50)) + .background(suitability.color.copy(alpha = 0.16f)) + .padding(horizontal = 12.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + suitability.label, + color = suitability.color, + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold + ) + if (score != null) { + Spacer(Modifier.width(6.dp)) + Text( + "$score", + color = suitability.color.copy(alpha = 0.85f), + style = MaterialTheme.typography.labelMedium + ) + } + } +} + +/** A thin horizontal meter showing the score out of 100. */ +@Composable +fun ScoreBar(score: Int, color: Color, modifier: Modifier = Modifier) { + Row( + modifier = modifier + .fillMaxWidth() + .height(6.dp) + .clip(RoundedCornerShape(50)) + .background(color.copy(alpha = 0.18f)) + ) { + Spacer( + Modifier + .fillMaxWidth(score.coerceIn(0, 100) / 100f) + .height(6.dp) + .background(color) + ) + } +} + +@Composable +fun MetricChip(metric: Metric) { + Column( + modifier = Modifier + .clip(RoundedCornerShape(10.dp)) + .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.75f)) + .padding(horizontal = 10.dp, vertical = 6.dp) + ) { + Text( + metric.label, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + metric.value, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium + ) + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun MetricChips(metrics: List, modifier: Modifier = Modifier) { + FlowRow( + modifier = modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + metrics.forEach { MetricChip(it) } + } +} + +@Composable +fun MetricSectionBlock(section: MetricSection) { + Column(Modifier.fillMaxWidth()) { + Text( + section.title, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary + ) + Spacer(Modifier.height(6.dp)) + MetricChips(section.metrics) + } +} + +/** A bulleted reason list, tinted to match its meaning (blocker, warning, highlight). */ +@Composable +fun ReasonList(title: String, reasons: List, color: Color) { + if (reasons.isEmpty()) return + Column(Modifier.fillMaxWidth().padding(top = 6.dp)) { + Text(title, style = MaterialTheme.typography.labelMedium, color = color) + reasons.forEach { reason -> + Text( + "• $reason", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/components/ConditionsCard.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/ConditionsCard.kt new file mode 100644 index 0000000..e27aa40 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/ConditionsCard.kt @@ -0,0 +1,369 @@ +package com.zenvairo.sportssuitability.ui.components + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.ExpandLess +import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material.icons.filled.Tune +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.zenvairo.sportssuitability.alerts.shortDayLabel +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.prefs.formatSnow +import com.zenvairo.sportssuitability.data.prefs.formatSnowDepth +import com.zenvairo.sportssuitability.data.prefs.formatTemp +import com.zenvairo.sportssuitability.data.prefs.formatWave +import com.zenvairo.sportssuitability.data.prefs.formatWind +import com.zenvairo.sportssuitability.data.repository.DailyConditions +import com.zenvairo.sportssuitability.data.repository.SpotConditions +import com.zenvairo.sportssuitability.data.repository.Suitability +import com.zenvairo.sportssuitability.data.repository.Verdict +import com.zenvairo.sportssuitability.data.repository.bestWindow +import com.zenvairo.sportssuitability.data.repository.dailyVerdict +import com.zenvairo.sportssuitability.data.repository.nowVerdict +import com.zenvairo.sportssuitability.data.repository.weatherCodeEmoji +import com.zenvairo.sportssuitability.data.repository.weatherCodeText +import com.zenvairo.sportssuitability.ui.MetricSection +import com.zenvairo.sportssuitability.ui.headlineMetrics +import com.zenvairo.sportssuitability.ui.nowSections +import com.zenvairo.sportssuitability.ui.color +import java.time.LocalDate + +@Composable +fun ConditionsCard( + conditions: SpotConditions, + settings: AppSettings, + onRemove: () -> Unit, + onEdit: () -> Unit, + onToggleAlerts: (Boolean) -> Unit +) { + var expanded by remember(conditions.spot.id) { mutableStateOf(false) } + var selectedDay by remember(conditions.spot.id) { mutableStateOf(null) } + + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant) + ) { + Column(Modifier.padding(16.dp)) { + CardHeader(conditions, settings, onEdit, onRemove) + + if (conditions.error != null) { + Text( + "Sin datos: ${conditions.error}", + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodyMedium + ) + return@Column + } + + val verdict = conditions.nowVerdict(settings) + Spacer(Modifier.height(10.dp)) + VerdictBlock(conditions, verdict, settings) + + conditions.partialWarning?.let { + Spacer(Modifier.height(6.dp)) + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + + val headline = conditions.headlineMetrics(settings) + if (headline.isNotEmpty()) { + Spacer(Modifier.height(12.dp)) + MetricChips(headline) + } + + val sections = conditions.nowSections(settings) + if (sections.isNotEmpty()) { + Spacer(Modifier.height(8.dp)) + ExpandToggle( + expanded = expanded, + collapsedLabel = "Ver todos los datos", + expandedLabel = "Ocultar detalle", + onToggle = { expanded = !expanded } + ) + AnimatedVisibility(visible = expanded) { + Column { + Spacer(Modifier.height(8.dp)) + SectionList(sections) + } + } + } + + if (conditions.days.isNotEmpty()) { + Spacer(Modifier.height(14.dp)) + HorizontalDivider() + Spacer(Modifier.height(10.dp)) + Text("Próximos días", style = MaterialTheme.typography.labelLarge) + Text( + "Toca un día para ver todos sus datos", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(8.dp)) + WeekStrip(conditions, settings) { selectedDay = it } + } + + Spacer(Modifier.height(12.dp)) + HorizontalDivider() + Row( + modifier = Modifier.fillMaxWidth().padding(top = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(Modifier.weight(1f)) { + Text("Avisarme por la mañana", style = MaterialTheme.typography.bodyMedium) + Text( + "Te diré si hoy puedes ir a este sitio", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch(checked = conditions.spot.alertsEnabled, onCheckedChange = onToggleAlerts) + } + } + } + + selectedDay?.let { day -> + DayDetailDialog( + conditions = conditions, + day = day, + settings = settings, + onDismiss = { selectedDay = null } + ) + } +} + +@Composable +private fun CardHeader( + conditions: SpotConditions, + settings: AppSettings, + onEdit: () -> Unit, + onRemove: () -> Unit +) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.Top + ) { + Column(Modifier.weight(1f)) { + Text( + conditions.spot.name, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold + ) + conditions.spot.region?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + conditions.now?.let { now -> + val sky = weatherCodeText(now.weatherCode) + if (sky != null) { + Text( + "${weatherCodeEmoji(now.weatherCode, now.isDay ?: true)} $sky", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + if (conditions.error == null) { + val verdict = conditions.nowVerdict(settings) + SuitabilityBadge(verdict.suitability, verdict.score) + } + IconButton(onClick = onEdit) { + Icon(Icons.Filled.Tune, contentDescription = "Ajustes del sitio") + } + IconButton(onClick = onRemove) { + Icon(Icons.Filled.Delete, contentDescription = "Eliminar sitio") + } + } +} + +/** The go / no-go answer, its score bar and the reasons behind it. */ +@Composable +private fun VerdictBlock(conditions: SpotConditions, verdict: Verdict, settings: AppSettings) { + val answer = when { + verdict.suitability == Suitability.UNKNOWN -> "Sin datos suficientes" + verdict.canGo -> "Hoy sí puedes ir" + verdict.blockers.isNotEmpty() -> "Hoy no: hay algo que lo impide" + else -> "Hoy mejor no: no llega al mínimo" + } + Text(answer, style = MaterialTheme.typography.titleSmall, color = verdict.suitability.color) + + verdict.score?.let { + Spacer(Modifier.height(6.dp)) + ScoreBar(it, verdict.suitability.color) + } + + conditions.today?.let { today -> + conditions.bestWindow(today.date, settings)?.let { (from, to) -> + Text( + "Mejor franja de hoy: $from – $to", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp) + ) + } + } + + ReasonList("Por qué no", verdict.blockers, Suitability.NO_GO.color) + ReasonList("A favor", verdict.highlights, Suitability.GOOD.color) + ReasonList("Ojo", verdict.warnings, Suitability.FAIR.color) +} + +@Composable +private fun ExpandToggle( + expanded: Boolean, + collapsedLabel: String, + expandedLabel: String, + onToggle: () -> Unit +) { + Row( + modifier = Modifier.fillMaxWidth().clickable(onClick = onToggle).padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + if (expanded) expandedLabel else collapsedLabel, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.primary + ) + Icon( + if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + } +} + +@Composable +fun SectionList(sections: List) { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + sections.forEach { MetricSectionBlock(it) } + } +} + +@Composable +private fun WeekStrip( + conditions: SpotConditions, + settings: AppSettings, + onDayClick: (DailyConditions) -> Unit +) { + val today = LocalDate.now() + LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + items(conditions.days, key = { it.date }) { day -> + DayCell( + day = day, + verdict = conditions.dailyVerdict(day, settings), + sportType = conditions.spot.sportType, + settings = settings, + today = today, + onClick = { onDayClick(day) } + ) + } + } +} + +@Composable +private fun DayCell( + day: DailyConditions, + verdict: Verdict, + sportType: SportType, + settings: AppSettings, + today: LocalDate, + onClick: () -> Unit +) { + Column( + modifier = Modifier + .width(76.dp) + .clip(RoundedCornerShape(12.dp)) + .background(verdict.suitability.color.copy(alpha = 0.14f)) + .clickable(onClick = onClick) + .padding(vertical = 8.dp, horizontal = 4.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + shortDayLabel(day.date, today), + style = MaterialTheme.typography.labelSmall, + fontSize = 11.sp, + fontWeight = FontWeight.Medium + ) + Text(weatherCodeEmoji(day.weatherCode), fontSize = 16.sp) + Text( + day.headline(sportType, settings), + style = MaterialTheme.typography.bodySmall, + fontSize = 12.sp, + textAlign = TextAlign.Center + ) + day.temperatureMaxC?.let { + Text( + it.formatTemp(settings.tempUnit), + style = MaterialTheme.typography.labelSmall, + fontSize = 10.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(Modifier.height(4.dp)) + Text( + verdict.score?.toString() ?: "–", + style = MaterialTheme.typography.labelSmall, + fontSize = 10.sp, + color = verdict.suitability.color, + fontWeight = FontWeight.SemiBold + ) + Spacer(Modifier.height(3.dp)) + Column( + Modifier + .height(5.dp) + .width(30.dp) + .clip(RoundedCornerShape(50)) + .background(verdict.suitability.color) + ) {} + } +} + +/** The single figure that best characterises a day for this sport. */ +private fun DailyConditions.headline(sportType: SportType, settings: AppSettings): String = + when (sportType) { + SportType.SURF -> waveHeightM?.formatWave(settings.waveUnit) ?: "–" + SportType.WINDSURF -> windSpeedKmh?.formatWind(settings.windUnit) ?: "–" + SportType.SKI -> when { + (snowfallCm ?: 0.0) >= 0.5 -> "+${snowfallCm!!.formatSnow(settings.snowUnit)}" + snowDepthCm != null -> snowDepthCm.formatSnowDepth(settings.snowUnit) + else -> "–" + } + } diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/components/DayDetailDialog.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/DayDetailDialog.kt new file mode 100644 index 0000000..6542fce --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/DayDetailDialog.kt @@ -0,0 +1,182 @@ +package com.zenvairo.sportssuitability.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.zenvairo.sportssuitability.alerts.dayOfWeekLabel +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.prefs.formatSnowDepth +import com.zenvairo.sportssuitability.data.prefs.formatTemp +import com.zenvairo.sportssuitability.data.prefs.formatWave +import com.zenvairo.sportssuitability.data.prefs.formatWind +import com.zenvairo.sportssuitability.data.repository.DailyConditions +import com.zenvairo.sportssuitability.data.repository.HourlyConditions +import com.zenvairo.sportssuitability.data.repository.SpotConditions +import com.zenvairo.sportssuitability.data.repository.Suitability +import com.zenvairo.sportssuitability.data.repository.bestWindow +import com.zenvairo.sportssuitability.data.repository.dailyVerdict +import com.zenvairo.sportssuitability.data.repository.hourlyVerdict +import com.zenvairo.sportssuitability.data.repository.weatherCodeEmoji +import com.zenvairo.sportssuitability.ui.daySections +import com.zenvairo.sportssuitability.ui.color +import java.time.LocalDate + +/** Everything known about one forecast day, including the hour-by-hour breakdown. */ +@Composable +fun DayDetailDialog( + conditions: SpotConditions, + day: DailyConditions, + settings: AppSettings, + onDismiss: () -> Unit +) { + val verdict = conditions.dailyVerdict(day, settings) + val hours = conditions.hours.filter { it.date == day.date } + + AlertDialog( + onDismissRequest = onDismiss, + title = { + Column { + Text(fullDayLabel(day.date), style = MaterialTheme.typography.titleMedium) + Text( + conditions.spot.name, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + }, + text = { + Column( + Modifier + .heightIn(max = 480.dp) + .verticalScroll(rememberScrollState()) + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + SuitabilityBadge(verdict.suitability, verdict.score) + Spacer(Modifier.width(10.dp)) + Text( + if (verdict.canGo) "Puedes ir" else "Mejor no ir", + style = MaterialTheme.typography.bodyMedium, + color = verdict.suitability.color + ) + } + verdict.score?.let { + Spacer(Modifier.height(8.dp)) + ScoreBar(it, verdict.suitability.color) + } + + conditions.bestWindow(day.date, settings)?.let { (from, to) -> + Text( + "Mejor franja: $from – $to", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 8.dp) + ) + } + + ReasonList("Por qué no", verdict.blockers, Suitability.NO_GO.color) + ReasonList("A favor", verdict.highlights, Suitability.GOOD.color) + ReasonList("Ojo", verdict.warnings, Suitability.FAIR.color) + + if (hours.isNotEmpty()) { + Spacer(Modifier.height(14.dp)) + HorizontalDivider() + Spacer(Modifier.height(10.dp)) + Text("Hora a hora", style = MaterialTheme.typography.labelLarge) + Spacer(Modifier.height(8.dp)) + HourStrip(conditions, hours, settings) + } + + Spacer(Modifier.height(14.dp)) + HorizontalDivider() + Spacer(Modifier.height(10.dp)) + SectionList(conditions.daySections(day, settings)) + } + }, + confirmButton = { + TextButton(onClick = onDismiss) { Text("Cerrar") } + } + ) +} + +@Composable +private fun HourStrip( + conditions: SpotConditions, + hours: List, + settings: AppSettings +) { + LazyRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + items(hours, key = { it.time }) { hour -> + val verdict = conditions.hourlyVerdict(hour, settings) + Column( + modifier = Modifier + .width(60.dp) + .clip(RoundedCornerShape(10.dp)) + .background(verdict.suitability.color.copy(alpha = 0.14f)) + .padding(vertical = 6.dp, horizontal = 3.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text(hour.hourLabel, style = MaterialTheme.typography.labelSmall, fontSize = 10.sp) + Text(weatherCodeEmoji(hour.weatherCode), fontSize = 13.sp) + Text( + hour.headline(conditions.spot.sportType, settings), + style = MaterialTheme.typography.labelSmall, + fontSize = 10.sp, + fontWeight = FontWeight.Medium + ) + hour.temperatureC?.let { + Text( + it.formatTemp(settings.tempUnit), + style = MaterialTheme.typography.labelSmall, + fontSize = 9.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(Modifier.height(3.dp)) + Column( + Modifier + .height(4.dp) + .width(24.dp) + .clip(RoundedCornerShape(50)) + .background(verdict.suitability.color) + ) {} + } + } + } +} + +private fun HourlyConditions.headline(sportType: SportType, settings: AppSettings): String = + when (sportType) { + SportType.SURF -> waveHeightM?.formatWave(settings.waveUnit) ?: "–" + SportType.WINDSURF -> windSpeedKmh?.formatWind(settings.windUnit) ?: "–" + SportType.SKI -> snowDepthCm?.formatSnowDepth(settings.snowUnit) + ?: windSpeedKmh?.formatWind(settings.windUnit) ?: "–" + } + +private fun fullDayLabel(date: String): String = runCatching { + val parsed = LocalDate.parse(date) + "${dayOfWeekLabel(parsed.dayOfWeek.value)} ${parsed.dayOfMonth}/${parsed.monthValue}" +}.getOrElse { date } diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/components/SpotSettingsDialog.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/SpotSettingsDialog.kt new file mode 100644 index 0000000..68f1b22 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/components/SpotSettingsDialog.kt @@ -0,0 +1,111 @@ +package com.zenvairo.sportssuitability.ui.components + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import com.zenvairo.sportssuitability.data.local.Spot +import com.zenvairo.sportssuitability.data.local.SportType + +/** Compass points offered for the coast orientation, with their bearing in degrees. */ +private val COMPASS_CHOICES = listOf( + "N" to 0.0, "NE" to 45.0, "E" to 90.0, "SE" to 135.0, + "S" to 180.0, "SO" to 225.0, "O" to 270.0, "NO" to 315.0 +) + +/** + * Per-spot tuning: which way the coast looks (so offshore wind can be detected) and, for ski + * resorts, the altitude the forecast should be taken at. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun SpotSettingsDialog( + spot: Spot, + onSetCoastFacing: (Double?) -> Unit, + onSetAltitude: (Double?) -> Unit, + onDismiss: () -> Unit +) { + var altitudeText by remember(spot.id) { + mutableStateOf(spot.altitudeM?.let { it.toInt().toString() } ?: "") + } + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(spot.name) }, + text = { + Column { + if (spot.sportType != SportType.SKI) { + Text("Orientación de la costa", style = MaterialTheme.typography.labelLarge) + Text( + "Hacia dónde miras cuando tienes el mar delante. Con esto la app " + + "distingue viento de tierra (offshore) de viento de mar (onshore).", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(8.dp)) + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + COMPASS_CHOICES.forEach { (label, degrees) -> + FilterChip( + selected = spot.coastFacingDeg == degrees, + onClick = { + onSetCoastFacing(if (spot.coastFacingDeg == degrees) null else degrees) + }, + label = { Text(label) } + ) + } + } + if (spot.coastFacingDeg == null) { + Text( + "Sin definir: la dirección del viento no puntúa.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } else { + Text("Altitud de la estación", style = MaterialTheme.typography.labelLarge) + Text( + "La previsión se pide a esta altura. Si dejas la del pueblo, verás " + + "lluvia donde en pistas está nevando.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = altitudeText, + onValueChange = { text -> + altitudeText = text.filter { it.isDigit() } + onSetAltitude(altitudeText.toDoubleOrNull()) + }, + label = { Text("Altitud") }, + suffix = { Text("m") }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth() + ) + } + } + }, + confirmButton = { TextButton(onClick = onDismiss) { Text("Listo") } } + ) +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SettingsScreen.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SettingsScreen.kt new file mode 100644 index 0000000..e10304c --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SettingsScreen.kt @@ -0,0 +1,544 @@ +package com.zenvairo.sportssuitability.ui.screens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Slider +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import com.zenvairo.sportssuitability.alerts.dayOfWeekLabel +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.prefs.Limit +import com.zenvairo.sportssuitability.data.prefs.LimitTunable +import com.zenvairo.sportssuitability.data.prefs.SnowUnit +import com.zenvairo.sportssuitability.data.prefs.TempUnit +import com.zenvairo.sportssuitability.data.prefs.Tunable +import com.zenvairo.sportssuitability.data.prefs.TunableGroup +import com.zenvairo.sportssuitability.data.prefs.ValueTunable +import com.zenvairo.sportssuitability.data.prefs.WaveUnit +import com.zenvairo.sportssuitability.data.prefs.WindUnit +import com.zenvairo.sportssuitability.data.prefs.fromDisplay +import com.zenvairo.sportssuitability.data.prefs.suffix +import com.zenvairo.sportssuitability.data.prefs.toDisplay +import com.zenvairo.sportssuitability.data.prefs.tunableGroups +import com.zenvairo.sportssuitability.ui.uiInfo +import kotlin.math.roundToInt + +@Composable +fun SettingsScreen( + settings: AppSettings, + onUpdate: ((AppSettings) -> AppSettings) -> Unit, + onResetSport: (SportType) -> Unit, + onTestDailyAlert: () -> Unit, + onTestWeeklyAlert: () -> Unit +) { + // Bumped whenever a change should force every text field to re-read from settings + // (unit switches, "restore defaults"), without fighting the user mid-keystroke. + var resetToken by remember { mutableIntStateOf(0) } + + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + item { + SettingsSection("Unidades") { + LabelledUnitRow("Viento", WindUnit.values().toList(), settings.windUnit, { it.label }) { unit -> + resetToken++ + onUpdate { it.copy(windUnit = unit) } + } + LabelledUnitRow("Olas", WaveUnit.values().toList(), settings.waveUnit, { it.label }) { unit -> + resetToken++ + onUpdate { it.copy(waveUnit = unit) } + } + LabelledUnitRow("Temperatura", TempUnit.values().toList(), settings.tempUnit, { it.label }) { unit -> + resetToken++ + onUpdate { it.copy(tempUnit = unit) } + } + LabelledUnitRow("Nieve", SnowUnit.values().toList(), settings.snowUnit, { it.label }) { unit -> + resetToken++ + onUpdate { it.copy(snowUnit = unit) } + } + } + } + + item { + SettingsSection( + title = "Exigencia", + description = "Puntuación mínima (0–100) para que la app diga que sí puedes ir. " + + "Súbela si sólo quieres saber de los días realmente buenos." + ) { + Text( + "Mínimo para ir: ${settings.minScoreToGo}", + style = MaterialTheme.typography.bodyMedium + ) + Slider( + value = settings.minScoreToGo.toFloat(), + onValueChange = { value -> + onUpdate { it.copy(minScoreToGo = value.roundToInt()) } + }, + valueRange = 0f..100f, + steps = 19 + ) + } + } + + item { AlertsSection(settings, onUpdate, onTestDailyAlert, onTestWeeklyAlert) } + + SportType.values().forEach { sport -> + item { + SportRulesHeader(sport) { + resetToken++ + onResetSport(sport) + } + } + item { SportPreferences(sport, settings, onUpdate) } + tunableGroups(sport).forEach { group -> + item { + TunableGroupCard( + group = group, + settings = settings, + resetToken = resetToken, + onUpdate = onUpdate + ) + } + } + } + + item { + Text( + "Los umbrales se guardan siempre en unidades métricas, así que cambiar de " + + "unidad no altera ninguna regla.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} + +// --------------------------------------------------------------------------- +// Alerts +// --------------------------------------------------------------------------- + +@Composable +private fun AlertsSection( + settings: AppSettings, + onUpdate: ((AppSettings) -> AppSettings) -> Unit, + onTestDailyAlert: () -> Unit, + onTestWeeklyAlert: () -> Unit +) { + val alerts = settings.alerts + SettingsSection("Avisos") { + SwitchRow( + title = "Aviso del día", + subtitle = "Cada mañana te digo si hoy puedes ir a los sitios que hayas marcado.", + checked = alerts.dailyEnabled + ) { enabled -> onUpdate { it.copy(alerts = it.alerts.copy(dailyEnabled = enabled)) } } + + if (alerts.dailyEnabled) { + TimeRow( + hour = alerts.dailyHour, + minute = alerts.dailyMinute, + onHourChange = { h -> onUpdate { it.copy(alerts = it.alerts.copy(dailyHour = h)) } }, + onMinuteChange = { m -> onUpdate { it.copy(alerts = it.alerts.copy(dailyMinute = m)) } } + ) + SwitchRow( + title = "Sólo si puedo ir", + subtitle = "Desactivado, también te aviso cuando no merece la pena, con el motivo.", + checked = alerts.dailyOnlyWhenGood + ) { only -> onUpdate { it.copy(alerts = it.alerts.copy(dailyOnlyWhenGood = only)) } } + } + + HorizontalDivider(Modifier.padding(vertical = 10.dp)) + + SwitchRow( + title = "Previsión semanal", + subtitle = "Un resumen de la semana que viene con los mejores días de cada sitio.", + checked = alerts.weeklyEnabled + ) { enabled -> onUpdate { it.copy(alerts = it.alerts.copy(weeklyEnabled = enabled)) } } + + if (alerts.weeklyEnabled) { + Text("Día", style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 8.dp)) + WeekdayPicker(alerts.weeklyDayOfWeek) { day -> + onUpdate { it.copy(alerts = it.alerts.copy(weeklyDayOfWeek = day)) } + } + TimeRow( + hour = alerts.weeklyHour, + minute = alerts.weeklyMinute, + onHourChange = { h -> onUpdate { it.copy(alerts = it.alerts.copy(weeklyHour = h)) } }, + onMinuteChange = { m -> onUpdate { it.copy(alerts = it.alerts.copy(weeklyMinute = m)) } } + ) + } + + Row( + Modifier.fillMaxWidth().padding(top = 12.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedButton(onClick = onTestDailyAlert, modifier = Modifier.weight(1f)) { + Text("Probar diario") + } + OutlinedButton(onClick = onTestWeeklyAlert, modifier = Modifier.weight(1f)) { + Text("Probar semanal") + } + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun WeekdayPicker(selected: Int, onSelect: (Int) -> Unit) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + (1..7).forEach { day -> + FilterChip( + selected = selected == day, + onClick = { onSelect(day) }, + label = { Text(dayOfWeekLabel(day).take(3)) } + ) + } + } +} + +@Composable +private fun TimeRow( + hour: Int, + minute: Int, + onHourChange: (Int) -> Unit, + onMinuteChange: (Int) -> Unit +) { + Row( + Modifier.fillMaxWidth().padding(top = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + IntField("Hora", hour, 0, 23, Modifier.weight(1f), onHourChange) + IntField("Minuto", minute, 0, 59, Modifier.weight(1f), onMinuteChange) + } +} + +@Composable +private fun IntField( + label: String, + value: Int, + min: Int, + max: Int, + modifier: Modifier = Modifier, + onChange: (Int) -> Unit +) { + var text by remember(value) { mutableStateOf(value.toString()) } + OutlinedTextField( + value = text, + onValueChange = { input -> + val digits = input.filter { it.isDigit() }.take(2) + text = digits + digits.toIntOrNull()?.takeIf { it in min..max }?.let(onChange) + }, + label = { Text(label) }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = modifier + ) +} + +// --------------------------------------------------------------------------- +// Per-sport rules +// --------------------------------------------------------------------------- + +@Composable +private fun SportRulesHeader(sport: SportType, onReset: () -> Unit) { + Row( + Modifier.fillMaxWidth().padding(top = 8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + "Reglas de ${sport.uiInfo().label}", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.primary + ) + OutlinedButton(onClick = onReset) { Text("Restaurar") } + } +} + +@Composable +private fun SportPreferences( + sport: SportType, + settings: AppSettings, + onUpdate: ((AppSettings) -> AppSettings) -> Unit +) { + when (sport) { + SportType.SURF -> SettingsSection("Dirección del viento") { + SwitchRow( + title = "Premiar viento offshore", + subtitle = "Necesita que hayas fijado la orientación de la costa en cada sitio.", + checked = settings.surf.preferOffshore + ) { value -> onUpdate { it.copy(surf = it.surf.copy(preferOffshore = value)) } } + } + SportType.WINDSURF -> SettingsSection("Dirección del viento") { + SwitchRow( + title = "Premiar viento cruzado", + subtitle = "Penaliza el offshore puro, que te empuja mar adentro.", + checked = settings.windsurf.preferSideShore + ) { value -> onUpdate { it.copy(windsurf = it.windsurf.copy(preferSideShore = value)) } } + } + SportType.SKI -> Unit + } +} + +@Composable +private fun TunableGroupCard( + group: TunableGroup, + settings: AppSettings, + resetToken: Int, + onUpdate: ((AppSettings) -> AppSettings) -> Unit +) { + SettingsSection(group.title, group.description) { + group.items.forEach { tunable -> + TunableRow(tunable, settings, resetToken, onUpdate) + Spacer(Modifier.height(4.dp)) + } + } +} + +@Composable +private fun TunableRow( + tunable: Tunable, + settings: AppSettings, + resetToken: Int, + onUpdate: ((AppSettings) -> AppSettings) -> Unit +) { + val suffix = tunable.kind.suffix(settings) + + when (tunable) { + is ValueTunable -> { + DoubleField( + fieldKey = "${tunable.id}-$resetToken-$suffix", + label = tunable.label, + help = tunable.help, + displayValue = tunable.kind.toDisplay(tunable.get(settings), settings), + suffix = suffix, + enabled = true, + onChange = { typed -> + onUpdate { current -> + tunable.set(current, tunable.kind.fromDisplay(typed, current)) + } + } + ) + } + + is LimitTunable -> { + val limit = tunable.get(settings) + Column(Modifier.fillMaxWidth().padding(top = 8.dp)) { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(Modifier.weight(1f)) { + Text(tunable.label, style = MaterialTheme.typography.bodyMedium) + Text( + if (limit.enabled) "Regla activa: impide ir" else "Regla desactivada", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = limit.enabled, + onCheckedChange = { enabled -> + onUpdate { current -> + tunable.set(current, tunable.get(current).copy(enabled = enabled)) + } + } + ) + } + tunable.help?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + DoubleField( + fieldKey = "${tunable.id}-$resetToken-$suffix", + label = "Valor", + help = null, + displayValue = tunable.kind.toDisplay(limit.value, settings), + suffix = suffix, + enabled = limit.enabled, + onChange = { typed -> + onUpdate { current -> + tunable.set( + current, + Limit( + enabled = tunable.get(current).enabled, + value = tunable.kind.fromDisplay(typed, current) + ) + ) + } + } + ) + } + } + } +} + +/** + * A decimal input that keeps its own text while being edited. [fieldKey] carries the reset + * token and the unit suffix, so the field re-reads from settings when either changes but + * never while the user is halfway through typing "1.". + */ +@Composable +private fun DoubleField( + fieldKey: String, + label: String, + help: String?, + displayValue: Double, + suffix: String, + enabled: Boolean, + onChange: (Double) -> Unit +) { + var text by remember(fieldKey) { mutableStateOf(formatValue(displayValue)) } + Column(Modifier.fillMaxWidth().padding(top = 6.dp)) { + OutlinedTextField( + value = text, + onValueChange = { input -> + text = input + input.replace(',', '.').toDoubleOrNull()?.let(onChange) + }, + label = { Text(label) }, + suffix = { Text(suffix) }, + enabled = enabled, + singleLine = true, + isError = text.replace(',', '.').toDoubleOrNull() == null, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), + modifier = Modifier.fillMaxWidth() + ) + help?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} + +// --------------------------------------------------------------------------- +// Small building blocks +// --------------------------------------------------------------------------- + +@Composable +private fun SettingsSection( + title: String, + description: String? = null, + content: @Composable ColumnScope.() -> Unit +) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant) + ) { + Column(Modifier.padding(16.dp)) { + Text(title, style = MaterialTheme.typography.titleSmall) + description?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + HorizontalDivider(Modifier.padding(vertical = 8.dp)) + content() + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun LabelledUnitRow( + label: String, + options: List, + selected: T, + optionLabel: (T) -> String, + onSelect: (T) -> Unit +) { + Column(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + Text(label, style = MaterialTheme.typography.labelLarge) + Spacer(Modifier.height(4.dp)) + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + options.forEach { option -> + FilterChip( + selected = option == selected, + onClick = { onSelect(option) }, + label = { Text(optionLabel(option)) } + ) + } + } + } +} + +@Composable +private fun SwitchRow( + title: String, + subtitle: String?, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit +) { + Row( + Modifier.fillMaxWidth().padding(vertical = 6.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyMedium) + subtitle?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + Spacer(Modifier.width(8.dp)) + Switch(checked = checked, onCheckedChange = onCheckedChange) + } +} + +private fun formatValue(v: Double): String { + val rounded = "%.1f".format(v) + return if (rounded.endsWith(".0")) rounded.dropLast(2) else rounded +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SportScreen.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SportScreen.kt new file mode 100644 index 0000000..1098336 --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/screens/SportScreen.kt @@ -0,0 +1,150 @@ +package com.zenvairo.sportssuitability.ui.screens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FloatingActionButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.pulltorefresh.PullToRefreshBox +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import com.zenvairo.sportssuitability.data.local.Spot +import com.zenvairo.sportssuitability.data.local.SportType +import com.zenvairo.sportssuitability.data.prefs.AppSettings +import com.zenvairo.sportssuitability.data.remote.GeocodingResult +import com.zenvairo.sportssuitability.data.repository.SpotConditions +import com.zenvairo.sportssuitability.ui.SearchUiState +import com.zenvairo.sportssuitability.ui.components.AddSpotDialog +import com.zenvairo.sportssuitability.ui.components.ConditionsCard +import com.zenvairo.sportssuitability.ui.components.SpotSettingsDialog +import com.zenvairo.sportssuitability.ui.uiInfo + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SportScreen( + sportType: SportType, + conditions: List, + isLoading: Boolean, + isRefreshing: Boolean, + searchState: SearchUiState, + settings: AppSettings, + onQueryChanged: (String) -> Unit, + onSearch: () -> Unit, + onPick: (GeocodingResult) -> Unit, + onRemove: (Spot) -> Unit, + onToggleAlerts: (Spot, Boolean) -> Unit, + onSetCoastFacing: (Spot, Double?) -> Unit, + onSetAltitude: (Spot, Double?) -> Unit, + onRefresh: () -> Unit, + onDismissSearch: () -> Unit +) { + var dialogOpen by remember { mutableStateOf(false) } + var editing by remember { mutableStateOf(null) } + val info = sportType.uiInfo() + + Scaffold( + floatingActionButton = { + FloatingActionButton(onClick = { dialogOpen = true }) { + Icon(Icons.Filled.Add, contentDescription = "Añadir sitio") + } + } + ) { padding -> + PullToRefreshBox( + isRefreshing = isRefreshing, + onRefresh = onRefresh, + modifier = Modifier.fillMaxSize().padding(padding) + ) { + when { + conditions.isEmpty() && isLoading -> + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + + conditions.isEmpty() -> + Column( + Modifier.fillMaxSize().padding(24.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + "Aún no has añadido sitios de ${info.label}.", + textAlign = TextAlign.Center + ) + Spacer(Modifier.height(4.dp)) + Text( + "Toca + para buscar uno.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + else -> + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + items(conditions, key = { it.spot.id }) { item -> + ConditionsCard( + conditions = item, + settings = settings, + onRemove = { onRemove(item.spot) }, + onEdit = { editing = item.spot }, + onToggleAlerts = { enabled -> onToggleAlerts(item.spot, enabled) } + ) + } + } + } + } + } + + if (dialogOpen) { + AddSpotDialog( + sportLabel = info.label, + state = searchState, + onQueryChanged = onQueryChanged, + onSearch = onSearch, + onPick = { result -> + onPick(result) + dialogOpen = false + onDismissSearch() + }, + onDismiss = { + dialogOpen = false + onDismissSearch() + } + ) + } + + editing?.let { spot -> + // Re-read the spot from the freshly loaded list so the dialog reflects saved edits. + val current = conditions.firstOrNull { it.spot.id == spot.id }?.spot ?: spot + SpotSettingsDialog( + spot = current, + onSetCoastFacing = { onSetCoastFacing(current, it) }, + onSetAltitude = { onSetAltitude(current, it) }, + onDismiss = { editing = null } + ) + } +} diff --git a/app/src/main/java/com/zenvairo/sportssuitability/ui/theme/Theme.kt b/app/src/main/java/com/zenvairo/sportssuitability/ui/theme/Theme.kt new file mode 100644 index 0000000..76b403f --- /dev/null +++ b/app/src/main/java/com/zenvairo/sportssuitability/ui/theme/Theme.kt @@ -0,0 +1,33 @@ +package com.zenvairo.sportssuitability.ui.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color + +private val Ocean = Color(0xFF0B72B9) +private val OceanDark = Color(0xFF7FC3EE) +private val Snow = Color(0xFF4FC3F7) + +private val LightColors = lightColorScheme( + primary = Ocean, + secondary = Snow +) + +private val DarkColors = darkColorScheme( + primary = OceanDark, + secondary = Snow +) + +@Composable +fun SportsSuitabilityTheme( + darkTheme: Boolean = isSystemInDarkTheme(), + content: @Composable () -> Unit +) { + MaterialTheme( + colorScheme = if (darkTheme) DarkColors else LightColors, + content = content + ) +} diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..922fb7b --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,8 @@ + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..376509e --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6b78462 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..6b78462 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..13d4518 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + SportsSuitability + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..f27daeb --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,4 @@ + + +