File size: 10,844 Bytes
e1f81b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import {ControllerTypes, DeviceTypes} from "@mentra/engine"
import {useRoute} from "@react-navigation/native"
import {Linking, PermissionsAndroid, Image, Platform, ScrollView, View} from "react-native"
import type {Permission} from "react-native"

import {MentraLogoStandalone} from "@/components/brands/MentraLogoStandalone"
import {Button, Header, Screen, Text} from "@/components/ignite"
import {useAppTheme} from "@/contexts/ThemeContext"
import {useNavigationStore} from "@/stores/navigation"
import {translate} from "@/i18n"
import {showAlert} from "@/utils/AlertUtils"
import {PermissionFeatures, checkConnectivityRequirementsUI, requestFeaturePermissions} from "@/utils/PermissionsUtils"
import {useState} from "react"
import GlassesTroubleshootingModal from "@/components/glasses/GlassesTroubleshootingModal"
import {engine} from "@mentra/engine"

type BluetoothPermission = Permission | "android.permission.BLUETOOTH" | "android.permission.BLUETOOTH_ADMIN"

export default function PairingPrepScreen() {
  const route = useRoute()
  const {deviceModel} = route.params as {deviceModel: string}
  const {goBack, push, clearHistoryAndGoHome} = useNavigationStore.getState()

  const advanceToPairing = async () => {
    if (deviceModel == null || deviceModel == "") {
      console.log("SOME WEIRD ERROR HERE")
      return
    }

    // Always request Bluetooth permissions - required for Android 14+ foreground service
    let needsBluetoothPermissions = true
    // we don't need bluetooth permissions for simulated glasses
    if (deviceModel.startsWith(DeviceTypes.SIMULATED) && Platform.OS === "ios") {
      needsBluetoothPermissions = false
    }

    try {
      // Check for Android-specific permissions
      if (Platform.OS === "android") {
        // Android-specific Phone State permission - request for ALL glasses including simulated
        console.log("Requesting PHONE_STATE permission...")
        const phoneStateGranted = await requestFeaturePermissions(PermissionFeatures.PHONE_STATE)
        console.log("PHONE_STATE permission result:", phoneStateGranted)

        if (!phoneStateGranted) {
          // The specific alert for previously denied permission is already handled in requestFeaturePermissions
          // We just need to stop the flow here
          return
        }

        // Bluetooth permissions only for physical glasses
        if (needsBluetoothPermissions) {
          const bluetoothPermissions: BluetoothPermission[] = []

          // Bluetooth permissions based on Android version
          if (typeof Platform.Version === "number" && Platform.Version < 31) {
            // For Android 9, 10, and 11 (API 28-30), use legacy Bluetooth permissions
            bluetoothPermissions.push("android.permission.BLUETOOTH")
            bluetoothPermissions.push("android.permission.BLUETOOTH_ADMIN")
          }
          if (typeof Platform.Version === "number" && Platform.Version >= 31) {
            bluetoothPermissions.push(PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN)
            bluetoothPermissions.push(PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT)
            bluetoothPermissions.push(PermissionsAndroid.PERMISSIONS.BLUETOOTH_ADVERTISE)
          }

          // Request Bluetooth permissions directly
          if (bluetoothPermissions.length > 0) {
            console.log("RIGHT BEFORE ASKING FOR PERMS")
            console.log("Bluetooth permissions array:", bluetoothPermissions)
            console.log(
              "Bluetooth permission values:",
              bluetoothPermissions.map((p) => `${p} (${typeof p})`),
            )

            const results = await PermissionsAndroid.requestMultiple(bluetoothPermissions as Permission[])
            const allGranted = Object.values(results).every((value) => value === PermissionsAndroid.RESULTS.GRANTED)

            // Since we now handle NEVER_ASK_AGAIN in requestFeaturePermissions,
            // we just need to check if all are granted
            if (!allGranted) {
              // Check if any are NEVER_ASK_AGAIN to show proper dialog
              const anyNeverAskAgain = Object.values(results).some(
                (value) => value === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN,
              )

              if (anyNeverAskAgain) {
                // Show "previously denied" dialog for Bluetooth
                showAlert(
                  translate("pairing:permissionRequired"),
                  translate("pairing:bluetoothPermissionPreviouslyDenied"),
                  [
                    {
                      text: translate("pairing:openSettings"),
                      onPress: () => Linking.openSettings(),
                    },
                    {
                      text: translate("common:cancel"),
                      style: "cancel",
                    },
                  ],
                )
              } else {
                // Show standard permission required dialog
                showAlert(
                  translate("pairing:bluetoothPermissionRequiredTitle"),
                  translate("pairing:bluetoothPermissionRequiredMessage"),
                  [{text: translate("common:ok")}],
                )
              }
              return
            }
          }

          // Phone state permission already requested above for all Android devices
        } // End of Bluetooth permissions block
      } // End of Android-specific permissions block

      // Check connectivity early for iOS (permissions work differently)
      console.log("DEBUG: needsBluetoothPermissions:", needsBluetoothPermissions, "Platform.OS:", Platform.OS)
      if (needsBluetoothPermissions && Platform.OS === "ios") {
        console.log("DEBUG: Running iOS connectivity check early")
        const requirementsCheck = await checkConnectivityRequirementsUI()
        if (!requirementsCheck) {
          return
        }
      }

      // Cross-platform permissions needed for both iOS and Android (only if connectivity check passed)
      if (needsBluetoothPermissions) {
        const hasBluetoothPermission = await requestFeaturePermissions(PermissionFeatures.BLUETOOTH)
        if (!hasBluetoothPermission) {
          showAlert(
            translate("pairing:bluetoothPermissionRequiredTitle"),
            translate("pairing:bluetoothPermissionRequiredMessageAlt"),
            [{text: translate("common:ok")}],
          )
          return // Stop the connection process
        }
      }

      // Android BLE scanning also requires location access.
      if (Platform.OS === "android") {
        console.log("Requesting location permission for Android BLE scanning...")

        // This now handles showing alerts for previously denied permissions internally
        const locGranted = await requestFeaturePermissions(PermissionFeatures.LOCATION)

        console.log("Location permission result:", locGranted)

        if (!locGranted) {
          // The specific alert for previously denied permission is already handled in requestFeaturePermissions
          // We just need to stop the flow here
          return
        }

        // Check connectivity for Android AFTER all permissions are granted
        // This must be done after location permission is granted to avoid premature "Connection issue" popup
        if (needsBluetoothPermissions) {
          const requirementsCheck = await checkConnectivityRequirementsUI()
          if (!requirementsCheck) {
            return
          }
        }
      } else {
        console.log("Skipping location permission on iOS - not needed after BLE fix")
      }
    } catch (error) {
      console.error("Error requesting permissions:", error)
      showAlert(translate("pairing:errorTitle"), translate("pairing:permissionsError"), [
        {text: translate("common:ok")},
      ])
      return
    }

    console.log("needsBluetoothPermissions", needsBluetoothPermissions)

    // Stop any running apps from previous sessions to prevent mic race conditions
    // This is symmetric with the logic in DeviceSettings that stops apps when unpairing
    // await useAppletStatusStore.getState().stopAllApplets()

    // skip pairing for simulated glasses:
    if (deviceModel.startsWith(DeviceTypes.SIMULATED)) {
      await engine.glasses.connectSimulated()
      clearHistoryAndGoHome()
      return
    }

    push("/pairing/scan-controller", {deviceModel})
  }

  const R1PairingGuide = () => {
    const {theme} = useAppTheme()

    return (
      <ScrollView

        className="flex-1 mt-6"

        contentContainerStyle={{paddingBottom: theme.spacing.s6}}

        showsVerticalScrollIndicator>

        <View className="flex-col items-center justify-center bg-primary-foreground rounded-xl mb-6">

          <Image

            source={require("../../../assets/glasses/even_realities/r1/ring.png")}

            resizeMode="contain"

            className="w-50 h-50"

          />

        </View>



        <View style={{justifyContent: "flex-start", flexDirection: "column"}}>

          <Text tx="pairing:instructions" className="text-2xl font-bold mb-4 text-secondary-foreground" />

          <Text className="text-lg text-secondary-foreground" tx="pairing:r1PreviousPhone" />

        </View>

      </ScrollView>
    )
  }

  const R1Buttons = () => {
    const [showTroubleshootingModal, setShowTroubleshootingModal] = useState(false)
    return (
      <>

        <View className="gap-4">

          <Button tx="pairing:g1Ready" onPress={advanceToPairing} />

          <Button tx="pairing:needMoreHelp" preset="secondary" onPress={() => setShowTroubleshootingModal(true)} />

        </View>

        <GlassesTroubleshootingModal

          isVisible={showTroubleshootingModal}

          onClose={() => setShowTroubleshootingModal(false)}

          deviceModel={deviceModel}

        />

      </>
    )
  }

  const renderGuide = () => {
    switch (deviceModel) {
      case ControllerTypes.R1:
        return <R1PairingGuide />
    }

    throw new Error(`Unknown model name: ${deviceModel}`)
  }

  const renderButtons = () => {
    switch (deviceModel) {
      case ControllerTypes.R1:
        return <R1Buttons />
      default:
        return <Button tx="common:continue" onPress={advanceToPairing} />
    }
  }

  return (
    <Screen preset="fixed" safeAreaEdges={["bottom"]} extraAndroidInsets>

      <Header

        title={deviceModel}

        leftIcon="chevron-left"

        onLeftPress={goBack}

        RightActionComponent={<MentraLogoStandalone />}

      />

      {renderGuide()}

      {renderButtons()}

    </Screen>
  )
}