import React from 'react';
import {
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  Image,
  ImageBackground,
  TouchableWithoutFeedback,
  Dimensions
} from 'react-native';
import { Button, Block, Text, Input, theme } from 'galio-framework';
import { products } from './products';
import { Product } from './Product';
import { AsyncStorage } from 'react-native';


//const personalPreferences = require('../constants/preferences.json');

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

const thumbMeasure = (width - 48 - 32) / 3;

// class structure from https://stackoverflow.com/questions/35022922/how-can-i-block-a-react-component-to-be-rendered-until-i-fetched-all-information
export default class Components extends React.Component {

    //IMPLEMENT OTHER JUNK HERE
    state = {
        'indexes': null //This is what our data will eventually be loaded into
    };

    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 {
        console.log("Trying to retrieve Data")
        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
    };

    componentDidMount() {
        this.loadData();
    }

    // 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.storeData()
        this.retrieveData().then((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)
            /*
            var scoreVal = 0;
            for (ll = 0; ll < 5; ll++){
              scoreVal += (products[i].values[ll]*(preferences[ll]/weightSum))
            }
            computedScores[i] = scoreVal*/
          }
          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){
                threeIndexes.push(k); 
                if (threeIndexes.length >= 3){
                  break dance;
                }
            }
            prevLargestVal = largestValue
          }
          console.log(threeIndexes)
          this.setState({
            'indexes': threeIndexes
          });
        }).catch((error) => {
          console.log('Promise is rejected with error: ' + error);
      }); 
    }

    renderCards = () => {
    //console.log(personalPreferences["preferences"]["comfort"]);
      console.log("outside then function")
      console.log(this.state.indexes)
      return (
        <Block flex style={styles.group}>
          <Text bold size={16} style={styles.title} onPress={() => this.props.navigation.navigate('ThingToDo')}>Netta's Top 3 Picks</Text>
          <TouchableWithoutFeedback onPress={() => this.handleClick()}>
          <Block flex>
            <Block style={{ paddingHorizontal: theme.SIZES.BASE }}>
              <Product product={products[this.state.indexes[0]]} horizontal />
              <Product product={products[this.state.indexes[1]]} horizontal />
              <Product product={products[this.state.indexes[2]]} horizontal />
            </Block>
          </Block>
          </TouchableWithoutFeedback>
        </Block>
      )
    }

    render() {
        if (!this.state.indexes) {
            return null
        }
        //WE HAVE DATA, DO A NORMAL RENDER
        return (
          <Block flex center>
            <ScrollView
              style={styles.components}
              showsVerticalScrollIndicator={false}>
                {this.renderCards()}
            </ScrollView>
          </Block>
        );
      }
}