import React, {Component} from "react";
import { ScrollView, StyleSheet, ImageBackground, TouchableHighlight, TouchableWithoutFeedback, Dimensions, Image, View, Modal, ActionSheetIOS, Picker, Platform, TouchableOpacity} from "react-native";
// Add Text and Image
import styles from "./style";
import { connect } from 'react-redux';
import { increment, increment_other } from '../../actions';
import { AsyncStorage } from "react-native";

//import { products } from './products';
//import { Product } from './Product';
import products  from '../Activity/products';
import friends  from '../Activity/friends';
import { Button, Block, Text, Input, theme } from 'galio-framework';
import {NavigationEvents} from 'react-navigation';

const { width } = Dimensions.get('screen');
const thumbMeasure = (width - 48 - 32) / 3;

class Product extends React.Component {

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

  /*

  <Block flex style={[styles2.imageContainer, styles2.shadow]}>
            <Image source={{ uri: product.image }} style={imageStyles} />
          </Block>

          <Block flex space="between" style={styles2.productDescription}>
            <Text size={26} style={styles2.productTitle}>{product.title}</Text>
            <Text style={styles2.matchText}>{matchScore}% match</Text>
            <Text style = {styles2.distanceText}>{product.distance} away</Text>
          </Block>

  */


  render() {
    const { navigation, product, horizontal, full, style, priceColor, imageStyle, index, matchScore, greyScale } = this.props;
    const imageStyles = styles2.image
    var greyScaleImagePath = product.greyImage
    var greyScaleArray = [
      require("./FogHarborFishHouse_greyscale.jpg"),
      require("./Surisan_greyscale.jpg"),
      require("./CarbonNightclub_greyscale.jpg"),
      require("./projectzenmassage_greyscale.jpg"),
      require("./MuseeMecanique_greyscale.jpg"),
      require("./Bimbo_greyscale.jpg"),
      require("./LombardStreet_greyscale.jpg"),
      require("./fishermanswharf_greyscale.jpg"),
      require("./carnival_greyscale.jpg"),
      require("./coittower_greyscale.jpg"),
    ];

    return (
      <Block row={horizontal} card style={greyScale ? [styles2.greyProduct, styles2.shadow] : [styles2.product, styles2.shadow]}>
        <Text style={greyScale ? styles2.greyProductTitle : styles2.productTitle}>
          {product.title}
        </Text>
        <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', overflow: 'hidden'}}>
          <Image source={greyScale ? greyScaleArray[index] : { uri: product.image }} style={imageStyles} />
          <View style={greyScale ? {width: 128, height: 128, backgroundColor: 'rgba(0, 0, 0, 0.5)', borderRadius: 64, alignItems: 'center', justifyContent: 'center', left: 38} : {width: 128, height: 128, backgroundColor: "#FFDF74", borderRadius: 64, alignItems: 'center', justifyContent: 'center', left: 38}}>
            <Text style={greyScale ? styles2.greyMatchText : styles2.matchText}>
              {matchScore}%
            </Text>
            <Text style={greyScale ? styles2.greySmallMatchText : styles2.smallMatchText}>
               match
            </Text>
          </View>
        </View>
        <View style={{marginTop: 8, marginBottom: 12, alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between', width: Dimensions.get('window').width - 36 - 8}}>
          <View style={{width: 50}}>
          </View>
          <View style={{flexDirection: 'row', justifyContent: 'space-between', width: 110}}>
            <Text style = {greyScale ? styles2.greyDistanceText : styles2.distanceText}>{product.distance} away</Text>
            <Image source={require('../locationImage2.png')} style={greyScale ? styles2.greyLocationImage : styles2.locationImage}/>
          </View>
          
        </View>
      </Block>
    );
  }
}

//export default withNavigation(Product);

const styles2 = StyleSheet.create({
  product: {
    backgroundColor: '#F2F5F7',
    marginVertical: theme.SIZES.BASE,
    borderWidth: 0,
    width: Dimensions.get('window').width - 36,
    minHeight: 227,
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'space-between',
  },
  greyProduct: {
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    marginVertical: theme.SIZES.BASE,
    borderWidth: 0,
    width: Dimensions.get('window').width - 36,
    minHeight: 227,
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'space-between',
  },
  productTitle: {
    color   :'#3F6072',
    fontWeight:'bold',
    textAlign: "center",
    fontSize: 24,
    marginTop: 8,
  },
  greyProductTitle: {
    color   :'rgba(0, 0, 0, 0.5)',
    fontWeight:'bold',
    textAlign: "center",
    fontSize: 24,
    marginTop: 8,
  },
  distanceText: {
    color   :'#3F6072',
    fontWeight:'bold',
    textAlign: "right",
    fontSize: 14,
  },
  greyDistanceText: {
    color   :'rgba(0, 0, 0, 0.5)',
    fontWeight:'bold',
    textAlign: "right",
    fontSize: 14,
  },
  matchText: {
    color:'#3F6072',
    fontWeight:'bold',
    textAlign: "right",
    fontSize: 24,
    width: 80,
    marginRight: 44,
  },
  greyMatchText: {
    color:'rgba(0, 0, 0, 0.5)',
    fontWeight:'bold',
    textAlign: "right",
    fontSize: 24,
    width: 80,
    marginRight: 44,
  },
  smallMatchText: {
    color:'#3F6072',
    fontWeight:'bold',
    textAlign: "right",
    fontSize: 16,
    width: 80,
    marginRight: 44,
  },
  greySmallMatchText: {
    color:'rgba(0, 0, 0, 0.5)',
    fontWeight:'bold',
    textAlign: "right",
    fontSize: 16,
    width: 80,
    marginRight: 44,
  },
  productDescription: {
    padding: theme.SIZES.BASE / 2,
  },
  imageContainer: {
    elevation: 1,
  },
  locationImage: {
    height: 20,
    width: 20,
    tintColor: '#587685',
  },
  greyLocationImage: {
    height: 20,
    width: 20,
    tintColor: 'rgba(0, 0, 0, 0.5)',
  },
  image: {
    borderRadius: 6,
    //marginHorizontal: theme.SIZES.BASE / 2,
   // marginTop: 5,
    height: 139,
    width: 201,
    marginLeft: 10,
   // marginBottom: 7,
  },
  shadow: {
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.5,
    shadowRadius: 3, 
    elevation: 2,
  },
});

class Home extends Component {
  static navigationOptions = {
    headerShown: false,
    isPopupVisible: false,
    gesturesEnabled: false,
    /*headerStyle: {
      backgroundColor: '#90CCF4',
      borderBottomWidth: 1,
    },*/
  };
  
  constructor(props) {
    super(props);
    this.state = {
      indexes: null,
      preferences: this.props.navigation.getParam("preferences"),
      calendarSync: this.props.navigation.getParam("calendarSync"),
      visitedList: [],
      matchScores: [],
      avoidList: [],
      isPopupVisible: false,
      forceRefresh: false,
      indexClicked: 0,
    };
    this.renderCards = this.renderCards.bind(this);
    this.loadData = this.loadData.bind(this);
    this.handleClick = this.handleClick.bind(this);
	this.traits = [
	  {
	    title: 'Comfort',
	    image: require('./home-icons/yoga.png'),
	  },
	  {
	    title: 'Socialness',
	    image: require('./home-icons/laugh.png')
	  },
	  {
	    title: 'Frugality',
	    image: require('./home-icons/money.png'),
	  },
		{
	    title: 'Art',
	    image: require('./home-icons/palette.png')
	  },
	  {
	    title: 'Food',
	    image: require('./home-icons/spaguetti.png')
	  },
	  ];
	  this.traitImages = [require('./home-icons/yoga.png'),
		require('./home-icons/laugh.png'),
		require('./home-icons/money.png'),
		require('./home-icons/palette.png'),
		require('./home-icons/spaguetti.png'),
	  ];
    console.log("On Home Screen")
    console.log(this.state.preferences)
  }

  componentWillMount(){
    AsyncStorage.clear();
  }

  componentDidMount() {
    this.loadData();
  }

  handleClick(){
    window.displayNum = 2
    this.props.navigation.navigate('ThingToDo')
  }

/*
  storeData = async () => {
    try {
      await AsyncStorage.setItem('personalPreferences', JSON.stringify([0, 0, 40, 0, 0]));
    } catch (error) {
      console.log("Error storing")
    }
  };*/

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

  computeMatchScore(indexes) {
    var values0 = products[indexes[0]].values
    var score0 = 80 + 20 * (this.cosinesim(values0, preferences));
    var values1 = products[indexes[1]].values
    var score1 = 80 + 20 * (this.cosinesim(values1, preferences));
    var values2 = products[indexes[2]].values
    var score2 = 80 + 20 * (this.cosinesim(values2, preferences));
    scoresArray = [score0, score1, score2]
    return scoresArray;
  }

  // from https://stackoverflow.com/questions/51362252/javascript-cosine-similarity-function
  cosinesim(A,B) {
    var dotproduct=0;
    var mA=0;
    var mB=0;
    for(i = 0; i < A.length; i++){ 
        dotproduct += (A[i] * B[i]);
        mA += (A[i]*A[i]);
        mB += (B[i]*B[i]);
    }
    mA = Math.sqrt(mA);
    mB = Math.sqrt(mB);
    var similarity = (dotproduct)/((mA)*(mB)) 
    var similarity = similarity.toFixed(1);
    return similarity;
  }

  loadData() {
 //     this.setState({forceRefresh: false})
    //this.storeData()
   // this.retrieveData().then(() => {
      console.log("Loading")
      preferences = this.state.preferences
      var computedScores = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      var i;
      var weightSum = 0;
      var threeIndexes = [];
      for (ll = 0; ll < 5; ll++){
        weightSum += preferences[ll]
      }
      for (var i = 0; i < 10; i++) {
        computedScores[i] = this.cosinesim(products[i].values, preferences)
      }
      sortedScores = [...computedScores]
      sortedScores.sort()
      sortedScores.reverse()
      var prevLargestVal = -1;
      dance:
      for (var j = 0; j < 10; j++){
        largestValue = sortedScores[j];
        var k = -1;
        while (((k = computedScores.indexOf(largestValue, k+1)) != -1) && prevLargestVal != largestValue){
            if(this.state.avoidList.find(elem => elem === k) !== undefined){
              continue
            }
            threeIndexes.push(k); 
            if (threeIndexes.length >= 3){
              break dance;
            }
        }
        prevLargestVal = largestValue
      }
      matchScores = this.computeMatchScore(threeIndexes);
      this.setState({
        'indexes': threeIndexes,
        'matchScores': matchScores,
      //  'preferences': preferences
      }); //    }).catch((error) => {
 //     console.log('Profile: Promise is rejected with error: ' + error);
  //  }); 
  }
  getModal(visible, isPopupVisible, indexClicked){
    if (isPopupVisible) {
      this.setState({ isPopupVisible: visible, indexClicked: indexClicked });
    }
  }


  getTraits(){
  	var computedScores = products[this.state.indexClicked].values
  	var twoIndexes = [];
	  sortedScores = [...computedScores]
	  sortedScores.sort()
	  sortedScores.reverse()
	  var prevLargestVal = -1;
	  dance:
	  for (var j = 0; j < 3; j++){
	    largestValue = sortedScores[j];
	    var k = -1;
	    while (((k = computedScores.indexOf(largestValue, k+1)) != -1) && prevLargestVal != largestValue){
	        twoIndexes.push(k); 
	        if (twoIndexes.length >= 2){
	          break dance;
	        }
	    }
	    prevLargestVal = largestValue
	  }
	  return twoIndexes
  }

  renderTraits(){
  	traitIndices = this.getTraits()
  	console.log(traitIndices)
  	console.log("TraitName:")
  	console.log(this.traits[traitIndices[0]].image)
  	return (
  	<View
        style={{
          flexDirection: 'row',
          alignSelf: 'center',
          marginTop: 20,
        }}
      >
     <View style={{
          marginRight: 10,
        }}>
        <Image
         style={styles.globePosition}
         source={this.traitImages[traitIndices[0]]}
       />
 		<Text style={{alignSelf: 'center',}}>{this.traits[traitIndices[0]].title}</Text>
 	</View>
 	<View style={{
          marginLeft: 10,
        }}>
  		<Image
         style={styles.globePosition}
         source={this.traitImages[traitIndices[1]]}
       />
 		<Text style={{alignSelf: 'center',}}>{this.traits[traitIndices[1]].title}</Text>
 	</View>
  	</View> )
  }

  renderCards(){
    console.log("Is modal visible:")
    console.log(this.state.isPopupVisible)
    var friendImages =   [
      require('../Activity/FriendPics/lexi-pic.jpeg'),
      require('../Activity/FriendPics/greg-pic.jpeg'),
      require('../Activity/FriendPics/jessica-pic.jpeg'),
      require('../Activity/FriendPics/soraya-pic.jpeg'),
      require('../Activity/FriendPics/jennifer-pic.jpeg'),
      require('../Activity/FriendPics/reid-pic.jpeg'),
      require('../Activity/FriendPics/grant-pic.jpeg'),
      require('../Activity/FriendPics/liz-pic.jpeg'),
      require('../Activity/FriendPics/kristen-pic.jpeg'),
      require('../Activity/FriendPics/samuel-pic.jpeg'),
    ];
    var greyFriendImages =   [
      require('./lexi-pic_greyscale.jpg'),
      require('./greg-pic_greyscale.jpg'),
      require('./jessica-pic_greyscale.jpg'),
      require('./soraya-pic_greyscale.jpg'),
      require('./jennifer-pic_greyscale.jpg'),
      require('./reid-pic_greyscale.jpg'),
      require('./grant-pic_greyscale.jpg'),
      require('./liz-pic_greyscale.jpg'),
      require('./kristen-pic_greyscale.jpg'),
      require('./samuel-pic_greyscale.jpg'),
    ];
    return (
      <Block flex style={styles.group}>
           <View style={styles.backgroundModal}>
          <Modal animationType = {"fade"} transparent = {true}
            visible = {this.state.isPopupVisible}>
            <View style = {styles.modalContainer}>
              <Text style={styles.modalText}>
              Why was this option picked?
              </Text>
              <Text style={styles.modalBody}>
               I find the best activities near you that fit your schedule and your interests! I chose this option because I learned from your survey and social media that you value:
              </Text>
             {this.renderTraits()}
              <TouchableHighlight style={styles.modalExit} onPress = {() => {
                this.getModal(!this.state.isPopupVisible, true, 0)}}>
                <Text style={styles.modalExitText}>X</Text>
              </TouchableHighlight>
            </View>
          </Modal>
        </View>
        <Block flex>
          <View style={{alignItems: 'center', marginBottom: 8}}>
            <View style={{width: Dimensions.get('window').width - 36, flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
              <TouchableOpacity style={this.state.isPopupVisible ? styles.greySettingButton : styles.settingButton} onPress={() => this.props.navigation.navigate('Chatbot', {prefArrayParam: this.state.preferences, indexParam: this.state.indexes, avoidList: this.state.avoidList, visitedList: this.state.visitedList, calendarSync: this.state.calendarSync})}>
                <Image source={require('../chatIcon.png')} style={styles.settingObject}/>
              </TouchableOpacity>
              <Text bold size={16} style={this.state.isPopupVisible ? styles.greyTitle : styles.title}>Your Top 3 Picks</Text>
              <TouchableOpacity style={this.state.isPopupVisible ? styles.greySettingButton : styles.settingButton} onPress={() => this.props.navigation.navigate("MainSettings", { preferences: this.state.preferences, calendarSync: this.state.calendarSync, visitedList: this.state.visitedList, avoidList: this.state.avoidList}) }>
                <Image source={require('../Activity/FriendPics/gear.png')} style={styles.settingObject}/>
              </TouchableOpacity>
            </View>
          </View>
          <Block style={{ paddingHorizontal: theme.SIZES.BASE }}>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Activity', {prefArrayParam: this.state.preferences, indexParam: this.state.indexes[0], calendarSync: this.state.calendarSync, visitedList: this.state.visitedList, avoidList: this.state.avoidList, matchParam: this.state.matchScores[0]})}>
              <Product product={products[this.state.indexes[0]]} greyScale={this.state.isPopupVisible} preferences = {this.state.preferences} index={this.state.indexes[0]} matchScore = {this.state.matchScores[0]} horizontal />
            </TouchableOpacity>
            <View
                style={{
                  flexDirection: 'row',
                  marginLeft: 10,
                }}
              >
                <TouchableOpacity style={this.state.isPopupVisible ? styles.greyQuestionContainer : styles.questionContainer} onPress={() => {this.getModal(true, true, this.state.indexes[0])}}>
                    <Text style={this.state.isPopupVisible ? styles.greyQuestionTextContainer :  styles.questionTextContainer}>?</Text>
                </TouchableOpacity>
	            	<View style={styles.friendContainer}>
	                <Image
	                     style={styles.circleImage}
	                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[0]].friendIndices[0]] : friendImages[products[this.state.indexes[0]].friendIndices[0]]}
	                   />
	                </View>
		                <View style={styles.friendContainer}>
		                <Image
		                     style={styles.circleImage}
		                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[0]].friendIndices[1]] : friendImages[products[this.state.indexes[0]].friendIndices[1]]}
		                   />
	                </View>
	                <View style={styles.friendContainer}>
	                <Image
	                     style={styles.circleImage}
	                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[0]].friendIndices[2]] : friendImages[products[this.state.indexes[0]].friendIndices[2]]}
	                   />
	                </View>
	                <View style={this.state.isPopupVisible ? styles.greyMoreFriendsContainer : styles.moreFriendsContainer}>
	                    <Text style={this.state.isPopupVisible ? styles.greyMoreFriendsTextContainer : styles.moreFriendsTextContainer}>+{products[this.state.indexes[0]].numFriends-3}</Text>
	                </View>
	          </View>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Activity',{prefArrayParam: this.state.preferences, indexParam: this.state.indexes[1], calendarSync: this.state.calendarSync, visitedList: this.state.visitedList, avoidList: this.state.avoidList, matchParam: this.state.matchScores[1]})}>
              <Product product={products[this.state.indexes[1]]} greyScale={this.state.isPopupVisible} preferences = {this.state.preferences} index={this.state.indexes[1]} matchScore = {this.state.matchScores[1]} horizontal />
            </TouchableOpacity>
          	<View
                style={{
                  flexDirection: 'row',
                  marginLeft: 10,
                }}
              >
                <TouchableOpacity style={this.state.isPopupVisible ? styles.greyQuestionContainer : styles.questionContainer} onPress={() => {this.getModal(true, true, this.state.indexes[1])}}>
                    <Text style={this.state.isPopupVisible ? styles.greyQuestionTextContainer :  styles.questionTextContainer}>?</Text>
                </TouchableOpacity>
                <View style={styles.friendContainer}>
                <Image
                     style={styles.circleImage}
                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[1]].friendIndices[0]] : friendImages[products[this.state.indexes[1]].friendIndices[0]]}
                   />
                </View>
                <View style={styles.friendContainer}>
                <Image
                     style={styles.circleImage}
                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[1]].friendIndices[1]] : friendImages[products[this.state.indexes[1]].friendIndices[1]]}
                   />
                </View>
                <View style={styles.friendContainer}>
                <Image
                     style={styles.circleImage}
                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[1]].friendIndices[2]] : friendImages[products[this.state.indexes[1]].friendIndices[2]]}
                   />
                </View>
                <View style={this.state.isPopupVisible ? styles.greyMoreFriendsContainer : styles.moreFriendsContainer}>
                    <Text style={this.state.isPopupVisible ? styles.greyMoreFriendsTextContainer : styles.moreFriendsTextContainer}>+{products[this.state.indexes[1]].numFriends-3}</Text>
                </View>
          </View>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Activity', {prefArrayParam: this.state.preferences, indexParam: this.state.indexes[2], calendarSync: this.state.calendarSync, visitedList: this.state.visitedList, avoidList: this.state.avoidList, matchParam: this.state.matchScores[2]})}>
              <Product product={products[this.state.indexes[2]]} greyScale={this.state.isPopupVisible} preferences = {this.state.preferences} index={this.state.indexes[2]} matchScore = {this.state.matchScores[2]} horizontal />
            </TouchableOpacity>
            <View
                style={{
                  flexDirection: 'row',
                  marginLeft: 10,
                }}
              >
                <TouchableOpacity style={this.state.isPopupVisible ? styles.greyQuestionContainer : styles.questionContainer} onPress={() => {this.getModal(true, true, this.state.indexes[2])}}>
                    <Text style={this.state.isPopupVisible ? styles.greyQuestionTextContainer :  styles.questionTextContainer}>?</Text>
                </TouchableOpacity>
                <View style={styles.friendContainer}>
                <Image
                     style={styles.circleImage}
                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[2]].friendIndices[0]] : friendImages[products[this.state.indexes[2]].friendIndices[0]]}
                   />
                </View>
                <View style={styles.friendContainer}>
                <Image
                     style={styles.circleImage}
                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[2]].friendIndices[1]] : friendImages[products[this.state.indexes[2]].friendIndices[1]]}
                   />
                </View>
                <View style={styles.friendContainer}>
                <Image
                     style={styles.circleImage}
                     source={this.state.isPopupVisible ? greyFriendImages[products[this.state.indexes[2]].friendIndices[2]] : friendImages[products[this.state.indexes[2]].friendIndices[2]]}
                   />
                </View>
                <View style={this.state.isPopupVisible ? styles.greyMoreFriendsContainer : styles.moreFriendsContainer}>
                    <Text style={this.state.isPopupVisible ? styles.greyMoreFriendsTextContainer : styles.moreFriendsTextContainer}>+{products[this.state.indexes[2]].numFriends-3}</Text>
                </View>
          </View>
          </Block>
        </Block>
        <View style={{alignItems: 'center', marginTop: 14}}>
        <View style={{flexDirection: 'row', alignItems: 'center', width: Dimensions.get('window').width - 36, justifyContent: 'space-between'}}>
          <Image source={this.state.isPopupVisible ? require('../globe_grayscale.png') : require('../globe.png')} style={styles.globePosition}/>
          <TouchableOpacity style={this.state.isPopupVisible ? styles.greyChatBotContainer : styles.chatBotContainer} onPress={() => { this.props.navigation.navigate('Chatbot', {prefArrayParam: this.state.preferences, indexParam: this.state.indexes, avoidList: this.state.avoidList, visitedList: this.state.visitedList, calendarSync: this.state.calendarSync})}}>
            <Text style={this.state.isPopupVisible ? styles.greyChatBotTextContainer : styles.chatBotTextContainer}>Don't like your options? Tell me what you want!</Text>
          </TouchableOpacity>
        </View>
        <View style={{height: 45}}>
        </View>
        </View>
        
      </Block>
    )
  }

 /* render() {
    const navigation = this.props.navigation;
    const increment = this.props.increment;
    const increment_other = this.props.increment_other;
    const i = this.props.i;
    const other = this.props.other;

    return (
      <View style={{flex:1, padding: 50}}>
        <Button onPress={() => {increment(); navigation.navigate('NotHome')}} title="You are at home" />
        <Text>i: {i}</Text>
        <Button onPress={() => {increment_other();}} title="Just increment" />
        <Text>other: {other}</Text>
      </View>
    );
  }*/

  screenAppears(){
    console.log("ME")
    console.log(this.props.navigation.getParam("visitedList"))
    console.log(this.props.navigation.getParam("preferences"))
    console.log(this.props.navigation.getParam("avoidList"))
    if (this.props.navigation.getParam("visitedList") === undefined){
      console.log("WOWEE")
    } else {
      console.log("YOYOOO")
      this.setState({preferences: this.props.navigation.getParam("preferences"), calendarSync: this.props.navigation.getParam("calendarSync"), visitedList: this.props.navigation.getParam("visitedList"), avoidList: this.props.navigation.getParam("avoidList") })
      console.log("OOOO")
      this.loadData()
      console.log("MOOOO")
    }
  }

  render() {
    const navigation = this.props.navigation;
    const increment = this.props.increment;
    const increment_other = this.props.increment_other;
    const i = this.props.i;
    const other = this.props.other;
    if (!this.state.indexes || !this.state.matchScores) {
        return null;
    }
    console.log('AVOIDLIST');
    console.log(this.state.avoidList);

  //  if (this.state.forceRefresh === true){
  //    this.loadData()
  //  }
    //WE HAVE DATA, DO A NORMAL RENDER
    return (
      <View flex center style={this.state.isPopupVisible ? {backgroundColor: 'rgba(0, 0, 0, 0.5)'} : ''}>
        <ScrollView
          style={styles.components}
          showsVerticalScrollIndicator={false}>
            {this.renderCards()}
        </ScrollView>
        <NavigationEvents onDidFocus={() => this.screenAppears()} />
      </View>
    );
  }
}

const mapStateToProps = (state) => {
    return {
      i: state.i,
      other: state.other,
    };
};
const mapDispatchToProps = (dispatch) => {
    return {
      increment: () => dispatch(increment()),
      increment_other: () => dispatch(increment_other()),
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);
