import { IReduxState } from 'interfaces' import axios from 'axios' import { ThunkDispatch } from 'redux-thunk' import { AnyAction } from 'redux' import { Platform, PermissionsAndroid } from 'react-native' import Geolocation from 'react-native-geolocation-service' import { SET_CURRENT_LOCATION, DEVICE_LOCATION_REJECTED, API_LOCATION_REJECTED, } from 'ducks/location' import { GeolocationPositionError } from './types' export const getDeviceLocation = async ( dispatch: ThunkDispatch, requestUrl: string, appId: string, language: string ): Promise => { let allowance if (Platform.OS === 'android') { allowance = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ) } else if (Platform.OS === 'ios') { allowance = await Geolocation.requestAuthorization('whenInUse') } switch (allowance) { case 'granted': return new Promise((resolve, reject) => { Geolocation.getCurrentPosition( async position => { const { coords } = position const { latitude, longitude } = coords try { const { data } = await axios.get(requestUrl, { params: { latitude, longitude, appId, language }, }) dispatch({ type: SET_CURRENT_LOCATION, payload: data, }) resolve() } catch (err: any) { dispatch({ type: API_LOCATION_REJECTED, payload: { message: err.response.data.message, code: err.response.status, }, }) reject() } }, err => { dispatch({ type: DEVICE_LOCATION_REJECTED, payload: new GeolocationPositionError(err.message, err.code), }) reject() }, { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 } ) }) case 'disabled': case 'denied': case 'restricted': dispatch({ type: DEVICE_LOCATION_REJECTED, payload: new GeolocationPositionError( `User ${allowance} geolocation`, 1 ), }) break default: dispatch({ type: DEVICE_LOCATION_REJECTED, payload: new GeolocationPositionError('Unable to retrieve location', 2), }) } }