import React, {Component} from "react";
import {Image, AsyncStorage, View,ScrollView, Slider, ActionSheetIOS, SafeAreaView, Dimensions, Picker, Text, Platform, TouchableOpacity, Button} from "react-native";
import styles from "./style";
import { connect } from 'react-redux';
import { Card } from 'react-native-elements';
import options from './optionsdata.js';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';


class Survey extends Component {
	state = {
    	'preferencesArray': this.props.navigation.getParam("preferences"), //This is what our data will eventually be loaded into
    	'pressFlags': [false, false, false, false, false, false, false, false, false, false, false, false],
    	'fromSettings': this.props.navigation.getParam("fromSettings"),
    };
	static navigationOptions = {headerShown: false, gesturesEnabled: false,};
	constructor(props) {
		super(props);
		this.renderButton = this.renderButton.bind(this);
		this.getOptionButton = this.getOptionButton.bind(this);
		this.activateButton = this.activateButton.bind(this);
		this.showBackButton = this.showBackButton.bind(this);
	}


  retrieveData = async () => {
      try {
        const rawValue = await AsyncStorage.getItem('personalPreferences');
        const parsedValue = JSON.parse(rawValue);
        return parsedValue;
      } catch (error) {
          console.log("Error retrieving")
      }
      return value
  };

  storeData = async () => {
    try {
      	await AsyncStorage.setItem('personalPreferences', JSON.stringify([1, 1, 1, 1, 1]));
	  	this.retrieveData().then((preferences) => {
		this.setState({
	        'preferencesArray': preferences
	      });
	    }).catch((error) => {
	      console.log('Promise rejected with error: ' + error);
	  }); 
    } catch (error) {
      console.log("Error storing")
    }
  };

  leaveScreen = async () => {
    try {
      await AsyncStorage.setItem('personalPreferences', JSON.stringify(this.state.preferencesArray));
     // this.props.navigation.navigate('SocialIntegration');
   	  if (this.state.fromSettings === true){
   	  	// Assuming array is passed around, fix this
   	  	// NOTE THIS SHOULD NOT SAY FALSE, it's a temp fix until we debug globeoutro
   	  	this.props.navigation.navigate("SocialIntegration", { preferences: this.state.preferencesArray}) 
   	  } else {
   	  	this.props.navigation.navigate("SocialIntegration", { preferences: this.state.preferencesArray}) 
   	  }
    } catch (error) {
      console.log("Error storing")
    }
  };

componentDidMount() {
    this.loadData();
}

loadData() {
	this.storeData()
}

//https://stackoverflow.com/questions/24094466/javascript-sum-two-arrays-in-single-iteration/27448893
updatePreferencesState(valuesArray, multiplier){
   	var sum = [];
    for (var i = 0; i < valuesArray.length; i++) {
        sum.push(this.state.preferencesArray[i] + multiplier * valuesArray[i]);
    }
    this.setState({'preferencesArray': sum});
}

activateButton(values, key){
	let keyValue = parseInt(key) - 1;
	let flags = [];
	for (let i = 0; i < this.state.pressFlags.length; i++){
		flags[i] = this.state.pressFlags[i];
	}
	if (flags[keyValue] === true){
		flags[keyValue] = false;
		this.updatePreferencesState(values, -1);
	} else {
		flags[keyValue] = true;
		this.updatePreferencesState(values, 1);
	}
	console.log(this.state.preferencesArray)
	this.setState({ pressFlags: flags });

}

getOptionButton(option, buttonPressed){
	if (buttonPressed === true){
		return (
			<TouchableOpacity
				style={styles.pressedButton}
				activeOpacity={.8}
				onPress={() => this.activateButton(option.values, option.key)}>
				<View style={{
					position: 'absolute',
					top: 6,
					height: 15,
					width: Dimensions.get('window').width * .4,
					marginTop: 0,
					backgroundColor: '#E0C465',
				    alignSelf: 'center',
				    shadowColor: 'rgba(0, 0, 0, 0.7)',
				    shadowOffset: {
				      width: 0,
				      height: -5
				    },
				    borderRadius: 10,
				    shadowRadius: 2,
				    shadowOpacity: .4
				}}>
				</View>
				<View style={{
					position: 'absolute',
					left: 3,
					top: 6,
					height: 144,
					width: 10,
					marginTop: 0,
					backgroundColor: '#E0C465',
				    shadowColor: 'rgba(0, 0, 0, 0.7)',
				    shadowOffset: {
				      width: -5,
				      height: 0,
				    },
				    borderRadius: 10,
				    shadowRadius: 2,
				    shadowOpacity: .4
				}}>
				</View>
				<Image source={option.icon} style={styles.optionImage}/>
				<Text style={styles.optionLabel}>
					{option.text}
				</Text>

			</TouchableOpacity>
		);
	} else  {
		return (
			<TouchableOpacity
				style={styles.startButton}
				activeOpacity={.8}
				onPress={() => this.activateButton(option.values, option.key)}>
				<Image source={option.icon} style={styles.optionImage}/>
				<Text style={styles.optionLabel}>
					{option.text}
				</Text>

			</TouchableOpacity>
		);
	}
	
}

renderButton(options){
	let optionList = []
	for (let i = 0; i < options.length; i++){
		let option = options[i];
		let keyValue = parseInt(option.key) - 1;
		optionList[i] = this.getOptionButton(option, this.state.pressFlags[keyValue]);
	}
	return optionList;
}

showBackButton(){
	if (this.state.fromSettings === true){
		return (
			<TouchableOpacity style={styles.prevButton} onPress={() => { this.props.navigation.navigate("MainSettings", { prefArrayParam: this.state.preferencesArray}) }}>
			   <Image source={require('./left.png')} style={styles.prevObject}/>
			 </TouchableOpacity>
		);
	}
	return;
}

render() {
    if (!this.state.preferencesArray) {
    	return null
     }
	const navigation = this.props.navigation;
	const screenWidth = Dimensions.get('window').width;
	console.disableYellowBox = true;
	//https://github.com/ReactNativeSchool/react-native-quiz/blob/master/App/data/computers.js
	//https://stackoverflow.com/questions/51629192/react-native-horizontal-scroll-on-button-click
	return (
		<ScrollView horizontal={true} scrollEnabled={false} pagingEnabled={true} showsHorizontalScrollIndicator={false} ref={(node) => this.scroll = node}>

			<View>
				<View style={styles.screenContainer}>
					<Text style={styles.textContainer}>{options[0].question}</Text>
				</View>
				<Text style={styles.textSelect}>
					Select all that apply
				</Text>
			<View style={styles.globeContainer}>
				<Image source={require('../globe.png')} style={styles.globePosition}/>
			</View>
			<View style={styles.buttonContainer}>
				{this.renderButton(options[0].options)}
			</View>
			{this.showBackButton()}
			<TouchableOpacity style={styles.nextButton} onPress={() => { this.scroll.scrollTo({ x: screenWidth }) }}>
			   <Image source={require('./right.png')} style={styles.nextObject}/>
			 </TouchableOpacity>
			<View style={styles.circleContainer}>
              <View style={styles.selectCircleObject}/>
              <View style={styles.circleObject}/>
              <View style={styles.circleObject}/>
            </View>
			</View>

			<View>
				<View style={styles.screenContainer}>
					<Text style={styles.textContainer}>
						{options[1].question}
					</Text>
				</View>
				<Text style={styles.textSelect}>
					Select all that apply
				</Text>
			<View style={styles.globeContainer}>
				<Image source={require('../globe.png')} style={styles.globePosition}/>
			</View>
			<View style={styles.buttonContainer}>
				{this.renderButton(options[1].options)}
			</View>
			<TouchableOpacity style={styles.prevButton} onPress={() => { this.scroll.scrollTo({ x: 0}) }}>
			   <Image source={require('./left.png')} style={styles.prevObject}/>
			 </TouchableOpacity>
			<TouchableOpacity style={styles.nextButton} onPress={() => { this.scroll.scrollTo({ x: screenWidth * 2 }) }}>
			   <Image source={require('./right.png')} style={styles.nextObject}/>
			 </TouchableOpacity>
			<View style={styles.circleContainer}>
              <View style={styles.circleObject}/>
              <View style={styles.selectCircleObject}/>
              <View style={styles.circleObject}/>
            </View>
			</View>

			<View>
				<View style={styles.screenContainer}>
					<Text style={styles.textContainer}>
						{options[2].question}
					</Text>
				</View>
				<Text style={styles.textSelect}>
					Select all that apply
				</Text>
			<View style={styles.globeContainer}>
				<Image source={require('../globe.png')} style={styles.globePosition}/>
			</View>
			<View style={styles.buttonContainer}>
				{this.renderButton(options[2].options)}
			</View>
			<TouchableOpacity style={styles.prevButton} onPress={() => { this.scroll.scrollTo({ x: screenWidth * 1}) }}>
			   <Image source={require('./left.png')} style={styles.prevObject}/>
			 </TouchableOpacity>
			<TouchableOpacity style={styles.nextButton} onPress={() => this.leaveScreen()}>
			   <Image source={require('./right.png')} style={styles.nextObject}/>
			 </TouchableOpacity>
			<View style={styles.circleContainer}>
              <View style={styles.circleObject}/>
              <View style={styles.circleObject}/>
              <View style={styles.selectCircleObject}/>
            </View>
			</View>

		</ScrollView>
		);
	}
}

export default Survey;
