Skip to content

Colota - Android GPS Location tracker

23.1 KB
Raw Blame
/**
 * Copyright (C) 2026 Max Dietrich
 * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
 */

import React, { useState, useEffect, useLayoutEffect, useCallback } from "react"
import { View, Text, StyleSheet, ScrollView, AppState } from "react-native"
import { useTheme } from "../hooks/useTheme"
import { useTracking } from "../contexts/TrackingProvider"
import { useTimeout } from "../hooks/useTimeout"
import { ProfileService } from "../services/ProfileService"
import NativeLocationService from "../services/NativeLocationService"
import { checkBluetoothPermission } from "../services/LocationServicePermission"
import { showAlert, showConfirm } from "../services/modalService"
import { TrackingProfile, ProfileConditionType, BluetoothDeviceInfo } from "../types/global"
import { fontSizes, fonts, lineHeights } from "../styles/typography"
import { SyncIntervalPicker } from "../components/features/settings/SyncIntervalPicker"
import {
  Button,
  Card,
  Container,
  Divider,
  FieldMessage,
  NumericInput,
  RadioRow,
  SectionTitle,
  SelectField,
  SettingRow,
  TextField
} from "../components"
import { Check, Trash2 } from "lucide-react-native"
import { logger } from "../utils/logger"
import { shortDistanceUnit, inputToMeters, metersToInput, getSpeedUnit, speedToInput, inputToSpeed } from "../utils/geo"
import { formatDuration, syncIntervalLabel } from "../utils/dashboardState"
import { conditionOf, profileSentence } from "../utils/profileRow"
import { parseWholeNumber, wholeNumberError } from "../utils/settingsValidation"
import { PROFILE_CONDITIONS, SAVE_SUCCESS_DISPLAY_MS, defaultProfileDelays, size, space } from "../constants"
import type { RootScreenProps } from "../types/navigation"
import { useTranslation } from "../i18n/useTranslation"

type Draft = Omit<TrackingProfile, "id" | "createdAt">
type NumericKey = "interval" | "distance" | "activationDelay" | "deactivationDelay" | "speed"

const DEFAULT_SPEED_INPUT = 30
const DEFAULT_PRIORITY = 10

const isSpeedType = (type: ProfileConditionType) => type === "speed_above" || type === "speed_below"

export function ProfileEditorScreen({ navigation, route }: RootScreenProps<"Profile Editor">) {
  const { colors } = useTheme()
  const { t } = useTranslation()
  const { settings } = useTracking()
  const profileId = route?.params?.profileId as number | undefined
  const isEditing = !!profileId
  const distanceUnit = shortDistanceUnit()
  const speedUnit = getSpeedUnit().unit

  const [profile, setProfile] = useState<Draft>({
    name: "",
    interval: settings.interval,
    distance: settings.distance,
    syncInterval: settings.syncInterval,
    priority: DEFAULT_PRIORITY,
    condition: { type: "charging" },
    ...defaultProfileDelays("charging"),
    enabled: true
  })
  const [saving, setSaving] = useState(false)
  const [currentSsid, setCurrentSsid] = useState("")
  // Survives a switch to another condition and back, like the typed network name.
  const [pickedDevice, setPickedDevice] = useState<BluetoothDeviceInfo | null>(null)
  const [btAllowed, setBtAllowed] = useState(true)
  const [text, setText] = useState({
    interval: String(settings.interval),
    distance: String(metersToInput(settings.distance)),
    speed: String(DEFAULT_SPEED_INPUT),
    priority: String(DEFAULT_PRIORITY),
    ssid: "",
    activationDelay: String(defaultProfileDelays("charging").activationDelay),
    deactivationDelay: String(defaultProfileDelays("charging").deactivationDelay)
  })
  const [note, setNote] = useState<{ key: NumericKey; text: string } | null>(null)
  const noteTimer = useTimeout()

  // Only fetched while the SSID field is open; the fallback keeps the offer button hidden.
  useEffect(() => {
    if (profile.condition.type !== "wifi_ssid") return

    const fetchSsid = () =>
      NativeLocationService.getCurrentSsid()
        .then(setCurrentSsid)
        .catch(() => setCurrentSsid(""))
    fetchSsid()

    // Connecting to a network in settings and coming back should reveal the offer.
    const sub = AppState.addEventListener("change", (state) => {
      if (state === "active") fetchSsid()
    })
    return () => sub.remove()
  }, [profile.condition.type])

  // Without Nearby devices the profile never matches, so the device field says so.
  useEffect(() => {
    if (profile.condition.type !== "bluetooth_device") return

    const readPermission = () => checkBluetoothPermission().then(setBtAllowed)
    readPermission()
    const sub = AppState.addEventListener("change", (state) => {
      if (state === "active") readPermission()
    })
    return () => sub.remove()
  }, [profile.condition.type])

  useLayoutEffect(() => {
    navigation.setOptions({ headerTitle: isEditing ? t("profileEditor.titleEdit") : t("profileEditor.titleNew") })
  }, [navigation, isEditing, t])

  useEffect(() => {
    if (!profileId) return
    ProfileService.getProfiles()
      .then((profiles) => {
        const existing = profiles.find((p) => p.id === profileId)
        if (!existing) return
        setProfile({
          name: existing.name,
          interval: existing.interval,
          distance: existing.distance,
          syncInterval: existing.syncInterval,
          priority: existing.priority,
          condition: existing.condition,
          activationDelay: existing.activationDelay,
          deactivationDelay: existing.deactivationDelay,
          enabled: existing.enabled
        })
        if (existing.condition.bluetoothAddress) {
          setPickedDevice({
            address: existing.condition.bluetoothAddress,
            name: existing.condition.bluetoothName ?? existing.condition.bluetoothAddress
          })
        }
        setText({
          interval: String(existing.interval),
          distance: String(metersToInput(existing.distance)),
          speed: String(
            existing.condition.speedThreshold ? speedToInput(existing.condition.speedThreshold) : DEFAULT_SPEED_INPUT
          ),
          priority: String(existing.priority),
          ssid: existing.condition.ssid ?? "",
          activationDelay: String(existing.activationDelay),
          deactivationDelay: String(existing.deactivationDelay)
        })
      })
      .catch((err) => {
        logger.error("[ProfileEditor] Failed to load profile:", err)
        showAlert(t("common.error"), t("profileEditor.loadFailed"), "error")
        navigation.goBack()
      })
  }, [profileId, navigation, t])

  const type = profile.condition.type
  const isSpeed = isSpeedType(type)
  const isStationary = type === "stationary"
  const isWifiSsid = type === "wifi_ssid"
  const isBluetooth = type === "bluetooth_device"
  const conditionLabel = t(conditionOf(profile).labelKey)

  const store = useCallback((key: NumericKey, value: number) => {
    setProfile((prev) => {
      if (key === "speed") return { ...prev, condition: { ...prev.condition, speedThreshold: inputToSpeed(value) } }
      if (key === "distance") return { ...prev, distance: inputToMeters(value) }
      return { ...prev, [key]: value }
    })
  }, [])

  const minOf = (key: NumericKey) => (key === "interval" || key === "speed" ? 1 : 0)
  const unitOf = (key: NumericKey) => (key === "distance" ? distanceUnit : key === "speed" ? speedUnit : t("unit.s"))

  const handleNumeric = (key: NumericKey, value: string) => {
    setText((prev) => ({ ...prev, [key]: value }))
    setNote(null)
    const num = parseWholeNumber(value)
    if (num !== null && num >= minOf(key)) store(key, num)
  }

  // An empty or below-minimum box clamps to the minimum on blur and says so, the Tracking & sync rule.
  const handleBlur = (key: NumericKey) => {
    const min = minOf(key)
    const num = parseWholeNumber(text[key])
    if (num !== null && num >= min) return
    setText((prev) => ({ ...prev, [key]: String(min) }))
    setNote({ key, text: t("validation.setTo", { value: min, unit: unitOf(key) }) })
    noteTimer.set(() => setNote(null), SAVE_SUCCESS_DISPLAY_MS)
    store(key, min)
  }

  const errorOf = (key: NumericKey) => wholeNumberError(text[key], minOf(key), unitOf(key))
  const noteOf = (key: NumericKey) => (note?.key === key ? note.text : undefined)

  const handleSsid = (value: string) => {
    setText((prev) => ({ ...prev, ssid: value }))
    setProfile((prev) => ({ ...prev, condition: { ...prev.condition, ssid: value } }))
  }
  const ssidError = isWifiSsid && text.ssid.trim() === "" ? t("profileEditor.wifi.empty") : undefined
  const offerCurrentSsid = currentSsid !== "" && currentSsid.trim().toLowerCase() !== text.ssid.trim().toLowerCase()

  const handleDevice = useCallback((device: BluetoothDeviceInfo) => {
    setPickedDevice(device)
    setProfile((prev) => ({
      ...prev,
      condition: { ...prev.condition, bluetoothAddress: device.address, bluetoothName: device.name }
    }))
  }, [])

  // The device screen hands its pick back through the route; clearing it stops a re-apply.
  const incomingDevice = route?.params?.bluetoothDevice
  useEffect(() => {
    if (!incomingDevice) return
    handleDevice(incomingDevice)
    navigation.setParams({ bluetoothDevice: undefined })
  }, [incomingDevice, handleDevice, navigation])
  const deviceError = isBluetooth && !pickedDevice ? t("profileEditor.bluetooth.empty") : undefined
  const priorityError =
    text.priority !== "" && parseWholeNumber(text.priority) === null ? t("validation.wholeNumber") : undefined
  const handlePriority = (value: string) => {
    setText((prev) => ({ ...prev, priority: value }))
    const num = parseWholeNumber(value)
    if (num !== null) setProfile((prev) => ({ ...prev, priority: num }))
  }
  const handlePriorityBlur = () => {
    if (parseWholeNumber(text.priority) === null) setText((prev) => ({ ...prev, priority: String(profile.priority) }))
  }

  const setConditionType = (next: ProfileConditionType) => {
    if (next === type) return
    const previousDefaults = defaultProfileDelays(type)
    const nextDefaults = defaultProfileDelays(next)
    const keepDelays =
      profile.activationDelay !== previousDefaults.activationDelay ||
      profile.deactivationDelay !== previousDefaults.deactivationDelay
    const delays = keepDelays
      ? { activationDelay: profile.activationDelay, deactivationDelay: profile.deactivationDelay }
      : nextDefaults
    const speedThreshold = isSpeedType(next)
      ? (profile.condition.speedThreshold ?? inputToSpeed(parseWholeNumber(text.speed) ?? DEFAULT_SPEED_INPUT))
      : undefined
    // Like the speed threshold, the typed network survives a switch away and re-seeds on the way
    // back; the stored column is cleared on save because the condition object drops it.
    const ssid = next === "wifi_ssid" ? (profile.condition.ssid ?? text.ssid) : undefined
    const device = next === "bluetooth_device" && pickedDevice ? pickedDevice : undefined
    setProfile((prev) => ({
      ...prev,
      ...delays,
      // A distance filter is ignored for a stationary profile; store 0 so UI, DB and runtime agree.
      distance: next === "stationary" ? 0 : prev.distance,
      condition: {
        type: next,
        ...(speedThreshold !== undefined ? { speedThreshold } : {}),
        ...(ssid !== undefined ? { ssid } : {}),
        ...(device ? { bluetoothAddress: device.address, bluetoothName: device.name } : {})
      }
    }))
    setText((prev) => ({
      ...prev,
      distance: next === "stationary" ? "0" : prev.distance,
      activationDelay: String(delays.activationDelay),
      deactivationDelay: String(delays.deactivationDelay),
      speed: speedThreshold !== undefined ? String(speedToInput(speedThreshold)) : prev.speed,
      ssid: ssid ?? prev.ssid
    }))
  }

  const handleDelete = useCallback(async () => {
    if (!profileId) return
    const confirmed = await showConfirm({
      title: t("profileEditor.delete.title"),
      message: t("profileEditor.delete.message", { name: profile.name || conditionLabel }),
      confirmText: t("common.delete"),
      destructive: true
    })
    if (!confirmed) return
    try {
      await ProfileService.deleteProfile(profileId)
      navigation.goBack()
    } catch (err) {
      logger.error("[ProfileEditor] Delete failed:", err)
      showAlert(t("common.error"), t("profileEditor.deleteFailed"), "error")
    }
  }, [profileId, profile.name, conditionLabel, navigation, t])

  const hasFieldError =
    !!priorityError ||
    !!errorOf("interval") ||
    (!isStationary && !!errorOf("distance")) ||
    (isSpeed && !!errorOf("speed")) ||
    !!ssidError ||
    !!deviceError ||
    !!errorOf("activationDelay") ||
    (!isStationary && !!errorOf("deactivationDelay"))

  const handleSave = useCallback(async () => {
    const next: Draft = {
      ...profile,
      name: profile.name.trim() || conditionLabel,
      condition: isWifiSsid ? { ...profile.condition, ssid: text.ssid.trim() } : profile.condition
    }
    setSaving(true)
    try {
      if (isEditing && profileId) {
        await ProfileService.updateProfile({ id: profileId, ...next })
      } else {
        await ProfileService.createProfile(next)
      }
      navigation.goBack()
    } catch (err) {
      logger.error("[ProfileEditor] Save failed:", err)
      showAlert(t("common.error"), t("profileEditor.saveFailed"), "error")
    } finally {
      setSaving(false)
    }
  }, [profile, conditionLabel, isEditing, isWifiSsid, text.ssid, profileId, navigation, t])

  const syncDefault = syncIntervalLabel(settings.syncInterval)

  return (
    <Container>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        <Text style={[styles.intro, { color: colors.textSecondary }]} testID="profile-sentence">
          {profileSentence(profile, settings.isOfflineMode)}
        </Text>

        <SectionTitle>{t("profileEditor.section.condition")}</SectionTitle>
        <Card rows>
          <View accessibilityRole="radiogroup" style={styles.group}>
            {PROFILE_CONDITIONS.map((opt) => (
              <React.Fragment key={opt.type}>
                <RadioRow
                  testID={`condition-${opt.type}`}
                  icon={opt.icon}
                  label={t(opt.labelKey)}
                  sub={t(opt.descriptionKey)}
                  selected={type === opt.type}
                  onPress={() => setConditionType(opt.type)}
                />
                {isSpeedType(opt.type) && type === opt.type && (
                  <View style={styles.reveal}>
                    <NumericInput
                      label={t("profileEditor.speed")}
                      testID="speed-input"
                      value={text.speed}
                      onChange={(v) => handleNumeric("speed", v)}
                      onBlur={() => handleBlur("speed")}
                      unit={speedUnit}
                      placeholder={String(DEFAULT_SPEED_INPUT)}
                      hint={t(
                        opt.type === "speed_above" ? "profileEditor.speed.hintAbove" : "profileEditor.speed.hintBelow",
                        { unit: speedUnit }
                      )}
                      error={errorOf("speed")}
                      message={noteOf("speed")}
                    />
                  </View>
                )}
                {opt.type === "wifi_ssid" && type === opt.type && (
                  <View style={styles.reveal}>
                    <TextField
                      label={t("profileEditor.wifi.ssid")}
                      testID="wifi-ssid-input"
                      mono
                      value={text.ssid}
                      onChangeText={handleSsid}
                      placeholder={t("trackingSync.ssid.placeholder")}
                      autoCapitalize="none"
                      autoCorrect={false}
                      error={ssidError}
                    />
                    <FieldMessage>{t("profileEditor.wifi.hint")}</FieldMessage>
                    {offerCurrentSsid && (
                      <Button
                        variant="secondary"
                        title={t("trackingSync.ssid.use", { ssid: currentSsid })}
                        testID="wifi-ssid-use"
                        onPress={() => handleSsid(currentSsid)}
                        style={styles.ssidUse}
                      />
                    )}
                  </View>
                )}
                {opt.type === "bluetooth_device" && type === opt.type && (
                  <View style={styles.reveal}>
                    <SelectField
                      label={t("profileEditor.bluetooth.device")}
                      testID="nav-bluetooth-device"
                      value={pickedDevice?.name}
                      placeholder={t("profileEditor.bluetooth.pick")}
                      error={deviceError ?? (btAllowed ? undefined : t("profileEditor.bluetooth.permission.title"))}
                      onPress={() => navigation.navigate("Bluetooth Device", { selected: pickedDevice ?? undefined })}
                    />
                  </View>
                )}
              </React.Fragment>
            ))}
          </View>
        </Card>

        <SectionTitle style={styles.groupTop}>{t("profileEditor.section.profile")}</SectionTitle>
        <Card rows style={styles.cardTop}>
          <View style={styles.field}>
            <TextField
              testID="name-input"
              label={t("profileEditor.name")}
              placeholder={conditionLabel}
              value={profile.name}
              onChangeText={(val) => setProfile((prev) => ({ ...prev, name: val }))}
            />
            <FieldMessage>{t("profileEditor.name.hint")}</FieldMessage>
          </View>
          <Divider tight />
          <SettingRow label={t("profileEditor.priority")} hint={t("profileEditor.priority.hint")}>
            <TextField
              accessibilityLabel={t("profileEditor.priority")}
              testID="priority-input"
              figure
              style={styles.numInput}
              keyboardType="numeric"
              value={text.priority}
              onChangeText={handlePriority}
              onBlur={handlePriorityBlur}
              placeholder={String(DEFAULT_PRIORITY)}
              error={priorityError}
            />
          </SettingRow>
        </Card>

        <SectionTitle style={styles.groupTop}>{t("profileEditor.section.tracking")}</SectionTitle>
        <Card rows style={styles.cardTop}>
          <NumericInput
            label={t("profileEditor.interval")}
            testID="interval-input"
            value={text.interval}
            onChange={(v) => handleNumeric("interval", v)}
            onBlur={() => handleBlur("interval")}
            unit={t("unit.s")}
            placeholder={String(settings.interval)}
            hint={t("profileEditor.interval.hint", { duration: formatDuration(settings.interval) })}
            error={errorOf("interval")}
            message={noteOf("interval")}
          />
          {isStationary ? (
            <SettingRow disabled label={t("trackingSync.distance")} hint={t("profileEditor.distance.stationary")}>
              <Text style={[styles.figure, { color: colors.textDisabled }]}>0 {distanceUnit}</Text>
            </SettingRow>
          ) : (
            <NumericInput
              label={t("trackingSync.distance")}
              testID="distance-input"
              value={text.distance}
              onChange={(v) => handleNumeric("distance", v)}
              onBlur={() => handleBlur("distance")}
              unit={distanceUnit}
              placeholder={String(metersToInput(settings.distance))}
              hint={t("profileEditor.distance.hint", {
                unit: distanceUnit,
                distance: `${metersToInput(settings.distance)} ${distanceUnit}`
              })}
              error={errorOf("distance")}
              message={noteOf("distance")}
            />
          )}
          {!settings.isOfflineMode && (
            <>
              <Divider tight />
              <View style={styles.pickerTop}>
                <SyncIntervalPicker
                  label={t("syncInterval.field")}
                  hint={t("profileEditor.sync.hint", { interval: syncDefault })}
                  value={profile.syncInterval}
                  min={0}
                  pullUp={false}
                  onSelect={(seconds) => setProfile((prev) => ({ ...prev, syncInterval: seconds }))}
                  onChange={(seconds) => setProfile((prev) => ({ ...prev, syncInterval: seconds }))}
                  onClamp={(seconds) => setProfile((prev) => ({ ...prev, syncInterval: seconds }))}
                />
              </View>
            </>
          )}
        </Card>

        <SectionTitle style={styles.groupTop}>{t("profileEditor.section.switching")}</SectionTitle>
        <Card rows style={styles.cardTop}>
          <NumericInput
            label={t("profileEditor.activation")}
            testID="activation-delay-input"
            value={text.activationDelay}
            onChange={(v) => handleNumeric("activationDelay", v)}
            onBlur={() => handleBlur("activationDelay")}
            unit={t("unit.s")}
            placeholder={String(defaultProfileDelays(type).activationDelay)}
            hint={isStationary ? t("profileEditor.activation.hintStationary") : t("profileEditor.activation.hint")}
            error={errorOf("activationDelay")}
            message={noteOf("activationDelay")}
          />
          {!isStationary && (
            <NumericInput
              label={t("profileEditor.deactivation")}
              testID="deactivation-delay-input"
              value={text.deactivationDelay}
              onChange={(v) => handleNumeric("deactivationDelay", v)}
              onBlur={() => handleBlur("deactivationDelay")}
              unit={t("unit.s")}
              placeholder={String(defaultProfileDelays(type).deactivationDelay)}
              hint={t("profileEditor.deactivation.hint")}
              error={errorOf("deactivationDelay")}
              message={noteOf("deactivationDelay")}
            />
          )}
        </Card>

        <Button
          testID="save-profile-btn"
          title={isEditing ? t("profileEditor.save") : t("profileEditor.create")}
          icon={Check}
          loading={saving}
          disabled={hasFieldError}
          onPress={handleSave}
          style={styles.save}
        />
        {isEditing && (
          <Button
            testID="delete-profile-btn"
            title={t("profileEditor.delete.title")}
            icon={Trash2}
            variant="danger"
            onPress={handleDelete}
          />
        )}
      </ScrollView>
    </Container>
  )
}

const styles = StyleSheet.create({
  scrollContent: { paddingHorizontal: space.lg, paddingTop: space.lg, paddingBottom: space.xxl },
  intro: { fontSize: fontSizes.body, ...fonts.regular, lineHeight: lineHeights.body, marginBottom: space.lg },
  group: { marginTop: -space.sm },
  groupTop: { marginTop: space.xl },
  cardTop: { paddingTop: space.lg },
  // The row above already pays space.lg below it; the field's own bottom margin is the card's tail.
  reveal: { paddingLeft: size.iconColumn, marginTop: -space.xs },
  ssidUse: { marginTop: space.sm, alignSelf: "flex-start" },
  field: { paddingBottom: space.lg },
  numInput: { width: size.numericField },
  figure: { fontSize: fontSizes.input, ...fonts.medium, fontVariant: ["tabular-nums"] },
  pickerTop: { paddingTop: space.lg },
  save: { marginTop: space.xl }
})