var characterList = require('./dev/characterlist.json')

let uniqueCharacters = characterList.filter((item, pos, self) => self.findIndex(c => c["Athenea"] == item["Athenea"]) == pos)

var newState = {}

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  WebView,
    Dimensions,
    ToolbarAndroid,
    StatusBar,
    ScrollView,
    Animated,
    FlatList,
    Image,
    TouchableNativeFeedback
} from 'react-native';
import ActionButton from 'react-native-action-button';
import Interactable from 'react-native-interactable';
import WebViewBridge from 'react-native-webview-bridge';

export default class TeXDraw extends Component {
    state = {
        _deltaY: new Animated.Value(0),
        _drawerPadding: new Animated.Value(38),
        recognitions:[],
        NNHasLoaded:false,
        toBeRecognized:""
    }
  render() {
    return (
        <View  style={{flex: 1}}>
        <View style={{flex: 1}}>
        <StatusBar
     backgroundColor="#8b0032"
     barStyle="light-content"
        style={{zIndex:1005}}
   />
        <ToolbarAndroid
            title="TeXDraw"
            titleColor="#ffffff"
            actions={[{title: 'Settings', icon: require('./icons/settings.png'), show: 'always'}]}
            style={{
        height: 56,
        backgroundColor: '#c1185b',
        zIndex:200,
        elevation:3,
    }}
      />
    <Animated.View style={{
        flex:1,
        backgroundColor: this.state._deltaY.interpolate({
              inputRange: [0, 0, Dimensions.get('window').height-130, Dimensions.get('window').height-130],
              outputRange: ['rgba(255, 0, 0, 1)','rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)', 'rgba(0, 255, 0, 1)']
            }),
        transform: [{
          translateY: this.state._deltaY.interpolate({
              inputRange: [0, 0, Dimensions.get('window').height-180, Dimensions.get('window').height-180],
              outputRange: [-250, -250, 0, 0]
            })
        }],
    }}>

        <WebView
        ref="webviewbridge"
        onMessage={this.onBridgeMessage.bind(this)}
        style={{marginTop: 0}}
        scrollEnabled={false}
        source={{uri:"file:///android_asset/main.html"}} />
    </Animated.View>

      </View>
      <Interactable.View
                ref="interactableView"
                dragEnabled={this.state.recognitions.length!=0}
  verticalOnly={true}
  initialPosition={{y: Dimensions.get('window').height-this.getDrawerHeight()}}
  //snapPoints={[{y: 200}, {y: Dimensions.get('window').height-130}]}
  springPoints={[{y: Dimensions.get('window').height-this.getDrawerHeight(), tension: 500, damping: 0.5, influenceArea: {top: Dimensions.get('window').height-250}}]}
  frictionAreas={[{damping: 0.9}]}
  alertAreas={[{id: 'myArea', influenceArea: {bottom: 56}}]}
  onAlert = {this.menuOpened.bind(this)}
  animatedValueY={this.state._deltaY}
  boundaries={{top: -2000, bottom:Dimensions.get('window').height, bounce:0}}
    style = {{
    position: 'absolute',
    backgroundColor:'#fdfdfd',       
    zIndex: 5,
    width:'100%',
    elevation:2
  }}>
        <Animated.View style={{
        transform: [{
          translateY: this.state._deltaY.interpolate({
              inputRange: [0, Dimensions.get('window').height-250, Dimensions.get('window').height-130, Dimensions.get('window').height-130],
              outputRange: [-38, -38, 0, 0]
            })
        }],
    }}>
        <Animated.View style={{padding:this.state._drawerPadding, backgroundColor:'#fdf1f6'}}>
      <Text style={{textAlign:'center', fontSize:18, padding:0, backgroundColor:'#fdf1f6'}}>{this.textToShow()}</Text>
      </Animated.View>
        <FlatList
          data={this.state.recognitions}
          renderItem={({item}) => 
          <TouchableNativeFeedback>
              <View style={{flexDirection: 'row', padding:5}}>
                <View style={{width: 80, height:80}}>
                  <Image source={{'uri': 'tex'+item.key}}
                        resizeMode="contain"
                        style={{alignSelf:'stretch', width: undefined, height: undefined, flex:1}}/>
                </View>
                <View style={{flexDirection: 'column'}}>
              <Text style={{fontSize:20, fontWeight:'normal', paddingTop:5, paddingLeft:10}}>{characterList[item.key]["Latex"]}</Text>
              <Text style={{fontSize:15, fontWeight:'normal', paddingTop:5, paddingLeft:10, color:"777777"}}>{characterList[item.key]["Package"]}</Text>
              </View>
            </View>
              </TouchableNativeFeedback>
            }
        />
        </Animated.View>
      </Interactable.View>
        <View style={{height:0}}>
        <WebViewBridge
        ref="texdrawwebview"
        style={{height:0}}
        allowUniversalAccessFromFileURLs={true}
        onBridgeMessage={this.onTeXDrawMessage.bind(this)}
        scrollEnabled={false}
        source={{uri:"file:///android_asset/texdraw.html"}}/>
        </View>
      <ActionButton
        offSetY={250}
  buttonColor="#c1185b"
  position="left"
  buttonText="x"
  degrees={45}
  onPress={this.clearCanvas.bind(this)}
  style={{zIndex:5, position:'absolute', bottom:100}}
  
/>
</View>
    );
  }
  
  onBridgeMessage(webViewData) {
      var str
      if(webViewData==undefined) str = this.state.toBeRecognized
      else str = webViewData.nativeEvent.data
      if(str=="[]"){
          this.setState({'recognitions':[]})
          newState = []
      }
      else{
          if(this.state.NNHasLoaded){
              this.refs.texdrawwebview.sendToBridge(str)
          }
          else{
              this.setState({'toBeRecognized':str})
              setTimeout(this.onBridgeMessage.bind(this),300)
          }
      }
  }

    onTeXDrawMessage(webViewData) {
        if(webViewData == "loaded"){
            //alert("loaded")
            this.refs.webviewbridge.postMessage("loaded");
            this.setState({'NNHasLoaded':true})
        }
        else{
          let jsonData = JSON.parse(webViewData);
          let result = Object.keys(jsonData).map(k => jsonData[k])
          let sorted = result.slice(0,).sort((a,b) => b-a)
          newState = sorted.slice(0,30).map(v => {
              let index = result.indexOf(v)
              return {key: index}
          })
          newState = newState.map(item => {
              return characterList.filter(c => c["Athenea"]==uniqueCharacters[item.key]["Athenea"]).map(c => characterList.findIndex(p => p["Latex"]==c["Latex"]))
          })
          //alert(JSON.stringify(newState))
          newState = Array.prototype.concat(...newState).map(n => ({"key":n}))
          //alert(JSON.stringify(newState))
          var ra = Math.floor(Math.random()*800)
          this.setState({'recognitions':newState.slice(0,5)})
          setTimeout((function(){
              this.setState({'recognitions':newState})
          }).bind(this), 400)
          setTimeout(Animated.timing(
              this.state._drawerPadding, {toValue: 10, duration:300}
            ).start, 50)
        }
    }


    clearCanvas() {
          this.refs.webviewbridge.postMessage("clear");
          setTimeout((function(){
              this.setState({'recognitions':[]})
              newState = []
          }).bind(this), 200)
    }

    menuOpened(e) {
        this.refs.interactableView.changePosition({x: 0, y: 56});
          this.refs.interactableView.setVelocity({y: 0});
    }

    textToShow(){
        if(this.state.recognitions.length==0){
            return 'Draw a symbol'
        }
        else{
            return 'Pull up for results'
        }
    }
    getDrawerHeight(){
        return 130
    }
}


const styles = StyleSheet.create({
   
});


AppRegistry.registerComponent('TeXDraw', () => TeXDraw);
