import React from 'react'; import { connect } from 'react-redux'; import { Text, View, Image, TouchableOpacity, Alert, Linking, AppState, Platform, } from 'react-native'; import Geolocation from '@react-native-community/geolocation'; import RNLocation from 'react-native-location'; import Theme from '../../../components/theme.style.js'; import CustomHeader from '../../../components/header.js'; import Elements from '../../../components/elements.js'; import DB from '../../../components/storage'; import REQUEST from '../../../components/api'; import NetInfo from "../../../components/netstatus"; import MapFragment from './fragments/map.js'; import PanelFragment from './fragments/stationpanel.js'; import SearchFragment from './fragments/searchbar.js'; import Assets from '../../../components/assets.manager.js'; import CustomSafeArea from '../../../components/safeArea.component.js'; import { navigate } from '../../../utils/navigation.js'; class Station extends React.Component { constructor(props) { super(props) this.dataLoader = null } state = { connected: false, loading: true, error: false, session: null, map: null, stationsViaCity: [], stations: [], markers: [], searchValue: "", showpanel: null, mylocation: {}, isSearched: false, isFavorite: false, initialRegion: { latitude: 14.599512, longitude: 120.984222, latitudeDelta: 15, longitudeDelta: 11 }, isGuest: false, appState: AppState.currentState, permissionLocation: true } componentDidMount () { this._isMounted = true; AppState.addEventListener('change', this._handleAppStateChange); this.props.navigation.addListener('focus', this.startTrackStation); } _handleAppStateChange = async (nextAppState) => { if(this.state.loading) return; if(this.state.appState.match(/inactive|background/) && nextAppState === 'active') { this.initLocationConfiguration() } this.setState({ appState: nextAppState }); } guestChecker = async () => { let isGuest = await DB.get('is_guest'); this.setState({ isGuest: isGuest }); return isGuest } fetch = async (location, successCallback, errorCallback) => { if(!location) return false let SESSION = await DB.session() const reqData = this.state.isGuest ? { longitude: location.longitude, latitude: location.latitude } : { lcard_uuid: SESSION.user.lcard_uuid, longitude: location.longitude, latitude: location.latitude } REQUEST('gas_stations', 'post', { Authorization: SESSION.token }, {}, reqData , async (res) => { this.renderMarkers(res.data) await successCallback(res) }, (error) => { console.log(error) errorCallback(error) }, "Gas stations", "Fetch") } renderMarkers = (data) => { if(data.length > 0) { let datamap = data.map((station, index) => { return { _id: index, latlng: {latitude: station.latitude, longitude: station.longitude}, station_uuid: station.station_uuid, name: station.name, address:station.address, longitude: station.longitude, latitude: station.latitude, stars: station.stars, favorite: station.favorite } }) this.setState({ markers: datamap }) } } goToRegion = (data) => { if(!data) return let newRegion = { latitude: parseFloat(data.latitude), longitude: parseFloat(data.longitude), latitudeDelta: 0.0043, longitudeDelta: 0.0034 } this.setState({ initialRegion: newRegion }) } navigate = (data) => { this.props.navigation.navigate('StationDetails', {markers: this.state.markers, data: data, theme: this.props.app_theme, onBackPress: () => this.initLocationConfiguration(), location: this.state.mylocation}) } startTrackStation = async () => { const guestChecker = await this.guestChecker(); if(guestChecker) { this.setState({ isGuest: guestChecker }) } NetInfo.netstatus(isConnected => { if(isConnected){ this.initLocationConfiguration() } else { Elements.nointernet2(this.props) } }) } initLocationConfiguration = () => { this.setState({ connected: true }) Geolocation.setRNConfiguration({ locationProvider: 'playServices', authorizationLevel: 'always' }); this.init() } init = () => { // if(this.state.isGuest) return; this.setState({ loading: true }) this.setState({ permissionLocation: true }); Geolocation.getCurrentPosition(latestLocation => { if(latestLocation.coords) { const coords = {longitude: latestLocation.coords.longitude, latitude: latestLocation.coords.latitude} this.setState({ mylocation: coords, error: false }) this.goToRegion(coords) setTimeout(() => { this.fetch(coords, success => { if(success.data){ this.setState({ showpanel: true, stations: success.data, loading: false }) this.goToRegion(success?.data.length > 0 ? success?.data[0] : coords) } else { this.goToRegion(coords) } }, error => { this.goToRegion(coords) this.setState({ error: false }) }) }, 3000) } }, err => { console.log(err) return Alert.alert("Information", '\n' + "Location GPS is disabled.", [{text: "OK", onPress: () => this.setState({ loading: false, permissionLocation: false })}]) }) } guestError = () => { Alert.alert( "Information", `\nApply for a card to enjoy this feature`, [ { text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: { color: 'red' }, }, { text: 'Enroll Card', onPress: () => navigate('Login') }, ] ); } getFavorites = async () => { this.setState({ searchValue: "My Favorites", loading: true }) let SESSION = await DB.session() REQUEST("station_favorites", "get", { Authorization: SESSION.token }, {}, {}, (res) => { if(res.data){ this.setState({ error: false, showpanel: true, stationsViaCity: res.data, loading: false, isFavorite: true }) this.goToRegion(res.data[0]) } }, (err) => { Alert.alert("Information", `\n${err.message}`); this.setState({ loading: false }) }, "Favorite Station", "Fetch") } onMapReady = () => { this.goToRegion(this.state.stations.length > 0 ? this.state.stations[0] : null); } openLink = () => { // if(this.state.isGuest) { // return Alert.alert("Information", "\nPlease login to continue", [{ // text: "CANCEL" // }, { // text: "OK", // onPress: async () => { // await DB.set("is_guest", "false", () => { // this.props.navigation.reset({ // index: 0, // routes: [{name: 'Login'}], // }) // }, () => {}); // } // } // ]) // } Platform.select({ ios: Linking.openURL("App-Prefs:Privacy&path=LOCATION"), android: Linking.sendIntent("android.settings.LOCATION_SOURCE_SETTINGS") }) } stationViaCity = async (city) => { this.setState({ searchValue: city.name, loading: true }) let SESSION = await DB.session() REQUEST("gas_stations_city", "get", { Authorization: SESSION.token }, { noID: true, value: city.city_uuid }, {}, (res) => { if(res.data.length > 0){ this.setState({ error: false, showpanel: true, isSearched: true, loading: false, stationsViaCity: res.data }) this.goToRegion(res.data[0]) } else if(res.message == 'Empty') { this.setState({ loading: false, isSearched: true, stationsViaCity: [] }) } }, (err) => { Alert.alert("Information", `\n${err.message}`); this.setState({ error: false }) }, "Station via city", "Fetch") } render() { if(!this.state.permissionLocation){ return ( This function needs your permission, please allow access. Allow on settings ) } if(!this.state.connected && !this.state.loading){ return ( this.startTrackStation()} /> ) } return ( this.state.isGuest ? {} : this.navigate(data)} /> this.setState({ searchValue: e.target.value })} onFocus={() => { this.props.navigation.navigate("StationSearch", { value: this.state.searchValue, onBackPress: (value, city, isFavorite) => { if(isFavorite){ return this.getFavorites() } else { this.stationViaCity(city) } } }) }} onClear={() => { this.setState({ searchValue: "", stationsViaCity: [], isFavorite: false }); setTimeout(() => { this.goToRegion(this.state.stations[0]) }, 2000) }} /> 0 ? this.state.stationsViaCity : this.state.stations} loading={this.state.loading} isSearched={this.state.isSearched} isFavorite={this.state.isFavorite} onClick={(data) => this.state.isGuest ? this.guestError() : this.navigate(data)} onUpdateFavorite={(index, update) => { if(this.state.searchValue){ let updatedStations = this.state.stationsViaCity updatedStations[index].favorite = update this.setState({ loading: true, stationViaCity: updatedStations }) } else { if(this.state.stationsViaCity.length > 0){ let updatedStations = this.state.stationsViaCity updatedStations[index].favorite = update this.setState({ loading: true, stationViaCity: updatedStations }) } else { let updatedStations = this.state.stations updatedStations[index].favorite = update this.setState({ loading: true, stations: updatedStations }) } } }} error={this.state.error && this.state.stations.length == 0 || this.state.error && this.state.stationsViaCity.length == 0} onError={() => this.initLocationConfiguration()} /> ) } } const mapStateToProps = (state) => { return { app_theme: state.appThemeReducer.theme } } export default connect(mapStateToProps, null)(Station);