import React from 'react';
import RNLocation from 'react-native-location';
import { connect } from 'react-redux';
import {
View,
Alert,
Image,
Linking,
Text,
TouchableOpacity,
SafeAreaView,
AppState
} from 'react-native';
import { saveUserInfo } from "../../redux/actions/AppUserInfoActions";
import Theme from '../../components/theme.style.js';
import NetInfo from "../../components/netstatus";
import CustomHeader from '../../components/header.js';
import Elements from '../../components/elements.js';
import DB from '../../components/storage';
import REQUEST from '../../components/api';
import REQUEST_POST_PAY from '../../components/api/postpayapi';
import Assets from '../../components/assets.manager.js';
import MapFragment from '../payatpump/fragments/map.js';
import PanelFragment from '../payatpump/fragments/stationpanel.js';
import SearchFragment from '../payatpump/fragments/searchbar.js';
import CustomSafeArea from '../../components/safeArea.component';
class Payatpump 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
}
watchID = null
componentDidMount() {
this._isMounted = true;
AppState.addEventListener('change', this._handleAppStateChange);
this.startTrackStation()
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange)
}
refreshProfileToken = async () => {
const SESSION = await DB.session()
this.props.saveUserInfo({ token: SESSION.token, card_number: SESSION.user.card_number }).then(res => {
DB.updateProfile(res, function(){}, function(error){})
})
}
_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 })
console.log(this.state.mylocation);
REQUEST_POST_PAY('getStores', 'get', {}, {
latitude: 14.580, //location.latitude, //uncomment this and replace the current value with this object
longitude: 121.026, //location.longitude, //uncomment this and replace the current value with this object
allowOutsidePayment: true
}, {}, async (res) => {
successCallback(res)
}, (error) => {
console.log(error)
errorCallback(error)
})
}
renderMarkers = (data) => {
if(data.length > 0) {
let datamap = data.map((station, index) => {
return {
_id: index,
latlng: {latitude: station.geoLocation.latitude, longitude: station.geoLocation.longitude},
station_uuid: station.storeId,
station_number: station.storeNumber,
name: station.storeName,
address: Object.entries(station.address).map(([key, value]) => `${value}`).join(',').toString(),
longitude: station.geoLocation.longitude,
latitude: station.geoLocation.latitude,
store: station
}
})
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('PayatpumpDetails', {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()
this.refreshProfileToken()
} 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 {
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, response => {
if(response.success){
this.setState({ showpanel: true, stations: response.response.data, loading: false })
this.renderMarkers(response.response.data)
this.goToRegion({longitude: response.response.data[0].geoLocation.longitude, latitude: response.response.data[0].geoLocation.latitude})
} 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, loading: 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 (
this.props.navigation.goBack()} navigation={this.props.navigation} />
this.startTrackStation()}
/>
)
}
if(!this.state.permissionLocation){
return (
this.props.navigation.goBack()} navigation={this.props.navigation} />
This function needs your permission, please allow access.
Linking.openSettings()}
style={{ padding: 15, backgroundColor: Theme.colors.primary, borderRadius: 5 }}>
Allow on settings
)
}
return (
this.props.navigation.goBack()} navigation={this.props.navigation} />
this.goToRegion(this.state.stations.length > 0 ? this.state.stations[0] : null)}
onMarkerClick={(data) => this.navigate(data)}
/>
{/* this.setState({ searchValue: e.target.value })}
onFocus={() => {
this.props.navigation.navigate("PayatpumpStationSearch", {
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])
}}
/> */}
0 ? this.state.stationsViaCity : this.state.stations}
loading={this.state.loading}
isSearched={this.state.isSearched}
onClick={(data) => this.navigate(data)}
snapPoints={['13', '10', '10']}
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()}/>
)
}
}
const mapStateToProps = (state) => {
return {
userinfo: state.appUserInfoReducer.userinfo,
app_theme: state.appThemeReducer.theme
}
}
const mapDispatchToProps = {
saveUserInfo
}
export default connect(mapStateToProps, mapDispatchToProps)(Payatpump)