<commit_before>'use strict';

var React                 = require('react-native');
var Icon                  = require('react-native-vector-icons/Ionicons');
var BackgroundGeolocation = require('react-native-background-geolocation');
var SettingsService       = require('./SettingsService');

var mapRef = 'mapRef';

// Map annotations stack.  pretty ugly business here.
// TODO MapboxGL doesn't handle annotations very well when we switch views (to Settings, for example), its annotations get all messed up.
// This needs work.
var annotations = [];

var {
  AsyncStorage,
  StyleSheet,
  MapView,
  AppStateIOS,
  Text,
  TextInput,
  View,
  SwitchIOS,
  Navigator,
  NavButton,
  TouchableHighlight
} = React;

var Map = React.createClass({
  
  getInitialState() {
    var me = this;
    
    AsyncStorage.getItem("state")
    .then((values) => {
      if (values !== null){
        values = JSON.parse(values);
        values.isStationary = true;
        me.setState(values);
        if (values.isEnabled) {
          me.onToggleEnabled(values.isEnabled);
        }
      } 
    })
    .catch((error) => console.error("- error: ", error.message))
    .done();

    AppStateIOS.addEventListener('change', this.onAppStateChange);

    this.bgGeo = BackgroundGeolocation;

    // Fetch bg-geo settings.
    SettingsService.getValues(function(values) {

      // Configure Background Geolocation.
      me.bgGeo.configure(values);

      me.bgGeo.getState(function(state) {
        console.log('------------ state: ', state);
      });

      // Listen to location events coming out.
      me.bgGeo.on('location', me.onBackgroundGeolocation);
      
      // Listen to motionchange events.
      me.bgGeo.on('motionchange', function(location) {
        console.log('- motionchanged: ', JSON.stringify(location));
        me.setState({
          isStationary: !location.is_moving,
          paceButtonStyle: (location.is_moving) ? styles.redButton : styles.greenButton
        });
      });

      // This fires after plugin successfully synced to server.
      me.bgGeo.on('sync', function(rs) {
        console.log('- sync complete: ', JSON.stringify(rs));
      })
    });

    return {
      zoom: 11,
      odometer: 0,
      isEnabled: false,
      isStationary: true,
      paceButtonStyle: styles.greenButton,
      navigateButton: 'navigate'
    };
  },
  onAppStateChange(state) {
    if (state === 'active') {
      var me = this;
      me.bgGeo.getCurrentPosition(function(location) {
        //me.setCenterCoordinateAnimated(mapRef, location.coords.latitude, location.coords.longitude);  
        console.log('- received current position: ', location);
      })      
    }
  },
  onClickSettings() {
    this.props.navigator.push({
      id: 'settings',
      sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
    });
  },
  onToggleEnabled(enabled) {
    var me = this;

    if (!enabled && !this.state.isStationary) {
      this.onToggleStationary();
    }
    this.setState({
      isEnabled: enabled,
      odometer: 0
    }, function() {
      AsyncStorage.setItem("state", JSON.stringify(me.state));
    });

    this.bgGeo.resetOdometer(function() {
      console.log('- resetOdometer success');
    });

    annotations = [];
    if (enabled) {
      this.bgGeo.start(function() {
        // Successfully started.  Now fetch current position.
        me.bgGeo.getCurrentPosition(function(location) {
          //me.setCenterCoordinateZoomLevelAnimated(mapRef, location.coords.latitude, location.coords.longitude, 14);
        });
      });
    } else {
      this.bgGeo.stop();
    }
  },
  onToggleStationary() {  
    var me = this;
    var value = !this.state.isStationary;

    this.setState({
      isStationary: value,
      paceButtonStyle: (value) ? styles.greenButton : styles.redButton
    });

    this.bgGeo.changePace(!value);
  },
  onUpdatePosition() {
    var me = this;
    this.setState({
      navigateButton: 'load-d'
    });
    me.bgGeo.getCurrentPosition(function(location) {
      //me.setCenterCoordinateAnimated(mapRef, location.coords.latitude, location.coords.longitude);
      me.setState({
        navigateButton: 'navigate'
      });
    });
  },
  onBackgroundGeolocation(location) {
    console.log('- [js] bgGeo location: ', JSON.stringify(location));
    var me    = this,
        now   = ((location.timestamp) ? new Date(location.timestamp) : new Date()),
        label = [now.getHours(), now.getMinutes(), now.getSeconds()].join(':');
    
    me.bgGeo.getOdometer(function(distance) {
      me.setState({
        odometer: (distance/1000).toFixed(1)
      });
    });

    // Push onto our annotations stack
    annotations.push({
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      title: label,
      annotationImage: {
        url: 'https://dl.dropboxusercontent.com/u/2319755/react-native-background-geolocation-demo/green-dot.png',
        height: 20,
        width: 20
      }
    });

    // Send annotations-stack to MapBoxGL.  Unfortunately, it has to destroy all existing then re-add...
    // TODO this needs to work better.  We need existing annotations to persist.  And we need polylines too.
    //me.addAnnotations(mapRef, annotations);
  },
  onRegionChange(location) {
    //this.setState({ currentZoom: location.zoom });
  },
  onRegionWillChange(location) {
    //console.log(location);
  },
  onUpdateUserLocation(location) {
    //console.log('[js]MapBox location: ', location);<commit_msg>DEbug location-error issue.  getGeofences issue<commit_after>'use strict';

var React                 = require('react-native');
var Icon                  = require('react-native-vector-icons/Ionicons');
var BackgroundGeolocation = require('react-native-background-geolocation');
var SettingsService       = require('./SettingsService');

var mapRef = 'mapRef';

var {
  AsyncStorage,
  StyleSheet,
  MapView,
  AppStateIOS,
  Text,
  TextInput,
  View,
  SwitchIOS,
  Navigator,
  NavButton,
  TouchableHighlight
} = React;

var Map = React.createClass({
  
  getInitialState() {
    var me = this;
    
    AsyncStorage.getItem("state")
    .then((values) => {
      if (values !== null){
        values = JSON.parse(values);
        values.isStationary = true;
        me.setState(values);
        if (values.isEnabled) {
          me.onToggleEnabled(values.isEnabled);
        }
      } 
    })
    .catch((error) => console.error("- error: ", error.message))
    .done();

    AppStateIOS.addEventListener('change', this.onAppStateChange);

    this.bgGeo = BackgroundGeolocation;

    // Fetch bg-geo settings.
    SettingsService.getValues(function(values) {

      // Configure Background Geolocation.
      me.bgGeo.configure(values);

      me.bgGeo.getState(function(state) {
        console.log('BackgroundGeolocation state: ', state);
      });

      // Listen to location events coming out.
      me.bgGeo.on('location', me.onBackgroundGeolocation);
      
      // Listen to motionchange events.
      me.bgGeo.on('motionchange', function(location) {
        console.log('- motionchanged: ', JSON.stringify(location));
        me.setState({
          isStationary: !location.is_moving,
          paceButtonStyle: (location.is_moving) ? styles.redButton : styles.greenButton
        });
      });

      // This fires after plugin successfully synced to server.
      me.bgGeo.on('sync', function(rs) {
        console.log('- sync complete: ', JSON.stringify(rs));
      });

      me.bgGeo.on('error', function(error) {
        alert(error.type + ' error: ' + error.code);
        console.log('- ERROR: ', error.type, error.code);
      });
    });

    return {
      zoom: 11,
      odometer: 0,
      isEnabled: false,
      isStationary: true,
      paceButtonStyle: styles.greenButton,
      navigateButton: 'navigate'
    };
  },
  onAppStateChange(state) {
    if (state === 'active') {
      var me = this;
      me.bgGeo.getCurrentPosition({timeout: 1000}, function(location) {
        console.log('- received current position: ', location);
      }, function(error) {
        alert('Location error: ' + error);
      });
    }
  },
  onClickSettings() {
    this.props.navigator.push({
      id: 'settings',
      sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
    });
  },
  onToggleEnabled(enabled) {
    var me = this;

    if (!enabled && !this.state.isStationary) {
      this.onToggleStationary();
    }
    this.setState({
      isEnabled: enabled,
      odometer: 0
    }, function() {
      AsyncStorage.setItem("state", JSON.stringify(me.state));
    });

    this.bgGeo.resetOdometer(function() {
      console.log('- resetOdometer success');
    });

    if (enabled) {
      this.bgGeo.start(function() {
        // Successfully started.  Now fetch current position.
        me.bgGeo.getCurrentPosition({timeout: 1000}, function(location) {
          console.log('[js] received current position: ', location);  
        }, function(error) {
          alert('Location error: ' + error);
        });
      });
    } else {
      this.bgGeo.stop();
    }
  },
  onToggleStationary() {  
    var me = this;
    var value = !this.state.isStationary;

    this.setState({
      isStationary: value,
      paceButtonStyle: (value) ? styles.greenButton : styles.redButton
    });

    this.bgGeo.changePace(!value);
  },
  onUpdatePosition() {
    var me = this;
    this.setState({
      navigateButton: 'load-d'
    });

    me.bgGeo.getCurrentPosition({timeout: 1000}, function(location) {
      me.bgGeo.getGeofences(function(rs) {
        console.log('- current geofences: ', rs);
      });
      me.setState({
        navigateButton: 'navigate'
      });
    }, function(error) {
      alert('Location error: ' + error);
      me.setState({
        navigateButton: 'navigate'
      });
    });
  },
  onBackgroundGeolocation(location) {
    console.log('- [js] bgGeo location: ', JSON.stringify(location));
    var me    = this,
        now   = ((location.timestamp) ? new Date(location.timestamp) : new Date()),
        label = [now.getHours(), now.getMinutes(), now.getSeconds()].join(':');
    
    me.bgGeo.getOdometer(function(distance) {
      me.setState({
        odometer: (distance/1000).toFixed(1)
      });
    });
  },
  onRegionChange(location) {
    //this.setState({ currentZoom: location.zoom });
  },
  onRegionWillChange(location) {
    //console.log(location);
  },
  onUpdateUserLocation(location) {
    //console.log('[js]MapBox location: ', location);
{'fraction_non_alphanumeric': 0.14156855298139004, 'fraction_numerical': 0.004082795290543107, 'mean_word_length': 2.5765704584040745, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2514950', 'n_tokens_mistral': 3260, 'n_tokens_neox': 3196, 'n_words': 602}