<commit_before>
var React = require('react-native');

/* ------ Components ------- */

var Message = require('./Message');
var CameraRoll = require('./CameraRoll.js');
var Camera = require('./Camera.js');

var MessageStreamSwitcher = require('./MessageStreamSwitcher.js');
var MessageTextInputButton = require('./MessageTextInputButton.js');
var NumHeartsDisplay = require('./NumHeartsDisplay.js');
var CameraRollButton = require('./CameraRollButton.js');
var ActionSheetIOS = require('ActionSheetIOS');
var imageButtons = ['From Camera','Photo Library','Cancel'];


/* ------ Configs ------- */

var HOST = require('../../../config.js');
var styles = require('../../../styles.js'); 

/* ------ React Components ------- */

var {

  View, 
  ListView, 
  Text, 
  ActivityIndicatorIOS, 
  TextInput, 
  TouchableOpacity, 
  Image, 
  NativeModules,
  Navigator,
  AlertIOS,

} = React;

/* ------ Main Component ------- */

class Messages extends React.Component {

  constructor(props) {
    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2
      }),
      loaded: false,
      reloading: false,
      coords: null,
      input: '',
      selectedImage: null,
      edit: false, 
    };

    this.displayName = "Messages"
  }

  componentDidMount() {
    this.fetchMessages();

    // Custom Navbar for Message Component
    if (this.props.navBar) {
      this.props.navBar = React.addons.cloneWithProps(this.props.navBar, {
        customNext: <MessageTextInputButton show={this._toggleEdit.bind(this)} />,
        customPrev: <NumHeartsDisplay userToken={this.props.userToken}/>,
      });
    }
  }

  render() {

    if ( !this.state.loaded || !this.props.userToken ) return null

    return (
      <View>
        {this.props.navBar}
        {this.state.edit ? 
        <View style={{backgroundColor: 'white',}}>
        <View style={{
          flexDirection:'row', 
          justifyContent: 'space-between', 
          alignItems: 'flex-end', 
          marginRight: 10, 
          marginTop: 10,
          backgroundColor: 'white', }}
        >
          <TextInput
            style={{height: 50, padding: 10, flex: 1, backgroundColor: 'white', fontFamily: 'Avenir', fontSize: 20}}
            editable={true}
            enablesReturnKeyAutomatically={false}
            autoCorrect={false}
            returnKeyType={'send'}
            placeholder={'Be nice and make a comment...'}
            value={this.state.input}
            onSubmitEditing={this._handleSubmit.bind(this)}
            clearButtonMode='while-editing'
            onChangeText={(text) => this.setState({input: text})}
          />
          <View style={{
            flexDirection:'row', 
            alignItems: 'flex-end', 
            justifyContent: 'space-between', 
            marginBottom: 10}}
          >
            <CameraRollButton
              navToCameraRoll={this._showImageOptions.bind(this)}
            />
          </View>
          </View>
          <View style={styles.seperator} />
        </View> : null }
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderMessage.bind(this)}
          renderHeader={this.renderHeader.bind(this)}
          style={{backgroundColor: 'white', height: require('Dimensions').get('window').height-62,}}
          initialListSize={10}
          pageSize={4}
          scrollRenderAheadDistance={2000} 
          onScroll={this._handleScroll.bind(this)}
        />
      </View>
      );
  }

  _toggleEdit(){
    this.setState({edit: this.state.edit ? false : true});
  }

  _handleSubmit(){
    if (!this.state.selectedImage) {
      this._submit();
    } else {
      this._postMessageWithImage();
    }
  }

  _postMessageWithImage(){
    var self = this;
    NativeModules.ReadImageData.processString(
      self.state.selectedImage.node.image.uri, 
      (image, imageWidth, imageHeight) => {
        self._submit(image, imageWidth, imageHeight);
    });
  }


  _submit(image, imageWidth, imageHeight){

    var watchError = (error) => {
      console.error(error);
      AlertIOS.alert(
        'Geolocation Error',
        'Please Turn on iOS Location Services'
      )
    }

    navigator.geolocation.getCurrentPosition((currentPosition)=>{

      var data = {
         x: currentPosition.coords.latitude,
         y: currentPosition.coords.longitude,
         z: currentPosition.coords.altitude,
         message: this.state.input,
         userToken: this.props.userToken,
       }

      if ( this.state.selectedImage ) {
        data.image = image;
        data.imageW = imageWidth;
        data.imageH = imageHeight;
      }

      fetch(HOST + 'messages', {
         method: 'POST',
         headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json'},
         body: JSON.stringify(data),

      }).then(()=> {
        this.setState({
          input:'', 
          selectedImage: null, 
          edit: false
        });
        this.fetchMessages();

      }).done();

   }, watchError);


  }

  _selectImage(image){
    this.setState({selectedImage: image})
  }

  _pushForwardToCameraRoll() {
    var selectImage = this._selectImage.bind(this);
    this.props.navigator.push({ 
      component: CameraRoll,
      navigator: this.props.navigator,
      selectImage: this._selectImage.bind(this), 
      sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
    });
  }

  _pushForwardToCamera() {
    this.props.navigator.push({ 
      component: Camera,
      navigator: this.props.navigator,
      selectImage: this._selectImage.bind(this), 
      sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
    });
  }

  _showImageOptions() {
    ActionSheetIOS.showActionSheetWithOptions({
      options: imageButtons,
      cancelButtonIndex: imageButtons.length-1
    },
    (buttonIndex) => {
      if (buttonIndex === 0){ //Camera
        this._pushForwardToCamera();
      }else if(buttonIndex === 1){ //Library
        this._pushForwardToCameraRoll();
      }<commit_msg>camera/ passing image data back to main view<commit_after>
var React = require('react-native');

/* ------ Components ------- */

var Message = require('./Message');
var CameraRoll = require('./CameraRoll.js');
var Camera = require('./Camera.js');

var MessageStreamSwitcher = require('./MessageStreamSwitcher.js');
var MessageTextInputButton = require('./MessageTextInputButton.js');
var NumHeartsDisplay = require('./NumHeartsDisplay.js');
var CameraRollButton = require('./CameraRollButton.js');
var ActionSheetIOS = require('ActionSheetIOS');
var imageButtons = ['From Camera','Photo Library','Cancel'];


/* ------ Configs ------- */

var HOST = require('../../../config.js');
var styles = require('../../../styles.js'); 

/* ------ React Components ------- */

var {

  View, 
  ListView, 
  Text, 
  ActivityIndicatorIOS, 
  TextInput, 
  TouchableOpacity, 
  Image, 
  NativeModules,
  Navigator,
  AlertIOS,

} = React;

/* ------ Main Component ------- */

class Messages extends React.Component {

  constructor(props) {
    this.state = {
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2
      }),
      loaded: false,
      reloading: false,
      coords: null,
      input: '',
      selectedImage: null,
      edit: false,
      cameraPhoto: false,
      imageData: null,
    };

    this.displayName = "Messages"
  }

  componentDidMount() {
    this.fetchMessages();

    // Custom Navbar for Message Component
    if (this.props.navBar) {
      this.props.navBar = React.addons.cloneWithProps(this.props.navBar, {
        customNext: <MessageTextInputButton show={this._toggleEdit.bind(this)} />,
        customPrev: <NumHeartsDisplay userToken={this.props.userToken}/>,
      });
    }
  }

  render() {

    if ( !this.state.loaded || !this.props.userToken ) return null

    return (
      <View>
        {this.props.navBar}
        {this.state.edit ? 
        <View style={{backgroundColor: 'white',}}>
        <View style={{
          flexDirection:'row', 
          justifyContent: 'space-between', 
          alignItems: 'flex-end', 
          marginRight: 10, 
          marginTop: 10,
          backgroundColor: 'white', }}
        >
          <TextInput
            style={{height: 50, padding: 10, flex: 1, backgroundColor: 'white', fontFamily: 'Avenir', fontSize: 20}}
            editable={true}
            enablesReturnKeyAutomatically={false}
            autoCorrect={false}
            returnKeyType={'send'}
            placeholder={'Be nice and make a comment...'}
            value={this.state.input}
            onSubmitEditing={this._handleSubmit.bind(this)}
            clearButtonMode='while-editing'
            onChangeText={(text) => this.setState({input: text})}
          />
          <View style={{
            flexDirection:'row', 
            alignItems: 'flex-end', 
            justifyContent: 'space-between', 
            marginBottom: 10}}
          >
            <CameraRollButton
              navToCameraRoll={this._showImageOptions.bind(this)}
            />
          </View>
          </View>
          <View style={styles.seperator} />
        </View> : null }
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderMessage.bind(this)}
          renderHeader={this.renderHeader.bind(this)}
          style={{backgroundColor: 'white', height: require('Dimensions').get('window').height-62,}}
          initialListSize={10}
          pageSize={4}
          scrollRenderAheadDistance={2000} 
          onScroll={this._handleScroll.bind(this)}
        />
      </View>
      );
  }

  _toggleEdit(){
    this.setState({edit: this.state.edit ? false : true});
  }

  _handleSubmit(){
    if (!this.state.selectedImage && !this.state.cameraPhoto) {
      this._submit();
    } else {
      this._postMessageWithImage();
    }
  }

  _postMessageWithImage(){
    var self = this;
    
    var dimensions = require('Dimensions').get('window');

    if (this.state.cameraPhoto){

      this._submit(this.state.imageData, dimensions.width, dimensions.height);
    }else{
      NativeModules.ReadImageData.processString(
        self.state.selectedImage.node.image.uri, 
        (image, imageWidth, imageHeight) => {
          self._submit(image, imageWidth, imageHeight);
      });
    }
  }

  _submit(image, imageWidth, imageHeight){

    var watchError = (error) => {
      console.error(error);
      AlertIOS.alert(
        'Geolocation Error',
        'Please Turn on iOS Location Services'
      )
    }

    navigator.geolocation.getCurrentPosition((currentPosition)=>{

      var data = {
         x: currentPosition.coords.latitude,
         y: currentPosition.coords.longitude,
         z: currentPosition.coords.altitude,
         message: this.state.input,
         userToken: this.props.userToken,
       }

      if ( this.state.selectedImage || this.state.cameraPhoto ) {
        data.image = image;
        data.imageW = imageWidth;
        data.imageH = imageHeight;
      }

      console.log(image, imageWidth, imageHeight, this.state.cameraPhoto, data)

      fetch(HOST + 'messages', {
         method: 'POST',
         headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json'},
         body: JSON.stringify(data),

      }).then(()=> {
        this.setState({
          input:'', 
          selectedImage: null, 
          edit: false
        });
        this.fetchMessages();

      }).done();

   }, watchError);

  }

  _selectImage(image){
    this.setState({ cameraPhoto: false })
    this.setState({ selectedImage: image })
  }

  _takePhoto(data){
    // The photo is returned as base64 data.
    // We don't need to encode again on submission.
    this.setState({ cameraPhoto: true })
    console.log(data)
    this.setState({ imageData: data });
  }

  _pushForwardToCameraRoll() {
    var selectImage = this._selectImage.bind(this);
    this.props.navigator.push({ 
      component: CameraRoll,
      navigator: this.props.navigator,
      selectImage: this._selectImage.bind(this), 
      sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
    });
  }

  _pushForwardToCamera() {
    this.props.navigator.push({ 
      component: Camera,
      navigator: this.props.navigator,
      takePhoto: this._takePhoto.bind(this), 
      sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
    });
  }

  _showImageOptions() {
    ActionSheetIOS.showActionSheetWithOptions({
      options: imageButtons,
      cancelButtonIndex: imageButtons.length-1
    },
    (buttonIndex) => {
      if (buttonIndex === 0){ //Camera
        this._pushForwardToCamera();
      }else if(buttonIndex === 1){ //Library
        this._pushForwardToCameraRoll();
      }
{'fraction_non_alphanumeric': 0.14322429906542056, 'fraction_numerical': 0.004672897196261682, 'mean_word_length': 2.2925641025641026, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 45, 'https://': 0, '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': '3419726', 'n_tokens_mistral': 3787, 'n_tokens_neox': 3657, 'n_words': 674}