import React from 'react';
import { withNavigation } from 'react-navigation';
import { StyleSheet, Dimensions, Image, TouchableWithoutFeedback } from 'react-native';
import { Block, Text, theme } from 'galio-framework';

import { AsyncStorage } from 'react-native';

const { width } = Dimensions.get('screen');

//class structure from https://stackoverflow.com/questions/35022922/how-can-i-block-a-react-component-to-be-rendered-until-i-fetched-all-information
class Product extends React.Component {
  state = {
      'matchScore': null //This is what our data will eventually be loaded into
  };


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

    componentDidMount() {
        this.loadData();
    }

    computeMatchScore(preferences) {
      const { navigation, product, horizontal, full, style, priceColor, imageStyle } = this.props;
      var score = 80 + 20 * (this.cosinesim(product.values, preferences));
      return score;
    }

    // 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.retrieveData().then((preferences) => {
        console.log("trying to compute match score")
        var matchScore = this.computeMatchScore(preferences)
        this.setState({
          'matchScore': matchScore
        });
      }).catch((error) => {
        console.log('Promise is rejected with error: ' + error);
    }); 
  }

  render() {
    console.log("HJKDHFKJHDSF")
    if (!this.state.matchScore) {
      return null
    }
    const { navigation, product, horizontal, full, style, priceColor, imageStyle } = this.props;
    console.log("HIHIHI")
    console.log(product)
    const imageStyles = [styles.image, full ? styles.fullImage : styles.horizontalImage, imageStyle];

    return (
      <Block row={horizontal} card flex style={[styles.product, styles.shadow, style]}>
          <Block flex style={[styles.imageContainer, styles.shadow]}>
            <Image source={{ uri: product.image }} style={imageStyles} />
          </Block>
          <Block flex space="between" style={styles.productDescription}>
            <Text size={14} style={styles.productTitle}>{product.title}</Text>
            <Text size={12} muted={!priceColor} color={priceColor}>{product.numFriends} friends went</Text>
            <Text size={12} muted={!priceColor} color={priceColor}>{product.distance}</Text>
            <Text size={12} muted={!priceColor} color={priceColor}>{this.state.matchScore}% match</Text>
          </Block>
      </Block>
    );
  }
}

export default withNavigation(Product);

const styles = StyleSheet.create({
  product: {
    backgroundColor: theme.COLORS.WHITE,
    marginVertical: theme.SIZES.BASE,
    borderWidth: 0,
    minHeight: 114,
  },
  productTitle: {
    flex: 1,
    flexWrap: 'wrap',
    paddingBottom: 6,
  },
  productDescription: {
    padding: theme.SIZES.BASE / 2,
  },
  imageContainer: {
    elevation: 1,
  },
  image: {
    borderRadius: 3,
    marginHorizontal: theme.SIZES.BASE / 2,
    marginTop: -16,
  },
  horizontalImage: {
    height: 122,
    width: 'auto',
  },
  fullImage: {
    height: 215,
    width: width - theme.SIZES.BASE * 3,
  },
  shadow: {
    shadowColor: theme.COLORS.BLACK,
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 4,
    shadowOpacity: 0.1,
    elevation: 2,
  },
});