unioil-loyalty-rn-app/app/screens/main/station/index.js

318 lines
10 KiB
JavaScript

import React from 'react';
import { connect } from 'react-redux';
import {
SafeAreaView,
Text,
View,
Image,
TouchableOpacity,
Alert,
Linking,
AppState
} from 'react-native';
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';
class Station extends React.Component {
constructor(props) {
super(props)
this.dataLoader = null
}
state = {
connected: false,
loading: false,
error: false,
session: null,
map: null,
stationsViaCity: [],
stations: [],
markers: [],
searchValue: "",
showpanel: null,
mylocation: {},
isSearched: false,
initialRegion: {
latitude: 14.599512,
longitude: 120.984222,
latitudeDelta: 15,
longitudeDelta: 11,
},
appState: AppState.currentState,
permissionLocation: false
}
componentDidMount() {
this._isMounted = true;
AppState.addEventListener('change', this._handleAppStateChange);
this.startTrackStation()
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
RNLocation.requestPermission({
ios: "whenInUse", // or 'always'
android: {
detail: "coarse"
}
}).then(granted => {
if(granted) {
this.init()
} else {
this.setState({ permissionLocation: false })
Alert.alert("Error", "Location GPS is disabled.")
}
})
}
this.setState({ appState: nextAppState });
}
fetch = async (location, successCallback, errorCallback) => {
if(!location) return false
this.setState({ loading: true })
let SESSION = await DB.session()
REQUEST('gas_stations', 'post', {
Authorization: SESSION.token
}, {}, {
lcard_uuid: SESSION.user.lcard_uuid,
longitude: location.longitude,
latitude: location.latitude
}, async (res) => {
successCallback(res)
}, (error) => {
errorCallback(error)
})
}
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 initialRegion = {
latitude: parseFloat(data.latitude),
longitude: parseFloat(data.longitude),
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}
this.setState({ initialRegion: initialRegion })
}
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 = () => {
NetInfo.netstatus(isConnected => {
if(isConnected){
this.initLocationConfiguration()
} else {
Elements.nointernet2(this.props)
}
})
}
initLocationConfiguration = () => {
this.setState({ connected: true })
RNLocation.configure({
// iOS Only
activityType: "other",
allowsBackgroundLocationUpdates: false,
headingFilter: 1, // Degrees
headingOrientation: "portrait",
pausesLocationUpdatesAutomatically: false,
showsBackgroundLocationIndicator: false,
})
RNLocation.requestPermission({
ios: "whenInUse", // or 'always'
android: {
detail: "coarse"
}
}).then(granted => {
if(granted) {
this.init()
} else {
this.setState({ permissionLocation: false })
Alert.alert("Error", "Location GPS is disabled.")
}
})
}
init = async () => {
this.setState({ permissionLocation: true })
RNLocation.getLatestLocation({ timeout: 20000 }).then(latestLocation => {
if(latestLocation != undefined) {
const coords = {longitude: latestLocation.longitude, latitude: latestLocation.latitude}
this.setState({ mylocation: coords, error: false })
this.goToRegion(coords)
this.fetch(coords, success => {
if(success.data){
this.setState({ showpanel: true, stations: success.data, loading: false })
this.renderMarkers(success?.data)
this.goToRegion(success?.data[0])
} else alert('Internal server error')
}, error => {
this.setState({ error: false })
})
}
})
}
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: [] })
} else alert('Internal server error')
}, (error) => {
this.setState({ error: false })
})
}
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 })
this.goToRegion(res.data[0])
} else alert('Internal server error')
}, (error) => {
this.setState({ loading: false })
})
}
render() {
if(!this.state.connected){
return (
<View style={{flex: 1}}>
<CustomHeader title="Stations" menu={true} navigation={this.props.navigation} />
<Elements.nointernet
message="No internet found. Please check your internet connection."
buttonText="Try Again"
onPress={() => this.startTrackStation()}
/>
</View>
)
}
if(!this.state.permissionLocation){
return (
<View style={{flex: 1}}>
<CustomHeader title="Stations" menu={true} navigation={this.props.navigation} />
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', marginHorizontal: 8 }}>
<Image source={Assets.icons.no_connection} style={{ width: 150, height: 120 }} />
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ color: this.props.app_theme?.theme.colors.text, fontSize: 15, padding: 15, textAlign: 'center' }}>This function needs your permission, please allow access.</Text>
<TouchableOpacity onPress={() => Linking.openSettings()}
style={{ padding: 15, backgroundColor: Theme.colors.primary, borderRadius: 5 }}>
<Text style={{ color: Theme.colors.white, fontSize: 15, textAlign: 'center' }}>Allow on settings</Text>
</TouchableOpacity>
</View>
</View>
</View>
)
}
return (
<CustomSafeArea>
<CustomHeader title="Stations" menu={true} navigation={this.props.navigation} />
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', height: Theme.screen.h, width: Theme.screen.w}}>
<MapFragment
region={this.state.initialRegion}
markers={this.state.markers}
onMapReady={() => this.goToRegion(this.state.stations.length > 0 ? this.state.stations[0] : null)}
onMarkerClick={(data) => this.navigate(data)}
/>
<SearchFragment
value={this.state.searchValue}
clear={this.state.searchValue != ""}
textColor={this.props.app_theme?.theme.colors.text}
isDarkMode={this.props.app_theme?.theme.dark}
searchBackgroundColor={this.props.app_theme?.theme.colors.border}
onChangeText={(e) => this.setState({ searchValue: e.target.value })}
onFocus={() => {
this.props.navigation.navigate("StationSearch", {
value: this.state.searchValue,
onBackPress: (value, city, isFavorite) => {
if(isFavorite){
this.getFavorites()
} else {
this.stationViaCity(city)
}
}
})
}}
onClear={() => {
this.setState({ searchValue: "", stationsViaCity: [] })
this.goToRegion(this.state.stations[0])
}}
/>
</View>
<PanelFragment
visible={this.state.showpanel}
data={this.state.searchValue ? this.state.stationsViaCity : this.state.stationsViaCity.length > 0 ? this.state.stationsViaCity : this.state.stations}
loading={this.state.loading}
isSearched={this.state.isSearched}
onClick={(data) => this.navigate(data)}
snapPoints={['8', '8', '8']}
onUpdateFavorite={(index, update) => {
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()}
/>
</CustomSafeArea>
)
}
}
const mapStateToProps = (state) => {
return {
app_theme: state.appThemeReducer.theme
}
}
export default connect(mapStateToProps, null)(Station);