import React from 'react';
import zxcvbn from 'zxcvbn';
import {
  Text,
  View,
  StyleSheet,
  ListView
} from 'react-native';
import _ from 'underscore';
import ResultItem from './ResultItem';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  } as React.ViewStyle,
  listView: {
    flex: 1
  } as React.ViewStyle,
  listItem: {
    flex: 1,
    borderBottomWidth: 1,
    borderBottomColor: '#333',
    paddingTop: 5,
    paddingBottom: 8,
  } as React.ViewStyle
});

const ITEM_ORDER = [
  'score',
  'calc_time',
  'guesses',
  'crack_times_display',
  'online_throttling_100_per_hour',
  'online_no_throttling_10_per_second',
  'offline_slow_hashing_1e4_per_second',
  'offline_fast_hashing_1e10_per_second',
  'feedback',
  'sequence'
];

interface Props {
  value: string;
}

interface State {}

export default class Results extends React.Component<Props, State> {
  dataSource: any;

  constructor() {
    super();
    this.dataSource = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
  }

  parseData(results: any) {
    let newResults = _.clone(results);
    const hashTimes = Object.keys(newResults.crack_times_display).map(function (key) {
      const value = newResults.crack_times_display[key];
      return {key, value};
    });
    const guesses = [{
      key: 'guesses',
      value: newResults.guesses * Math.pow(10, newResults.guesses_log10)
    }];
    delete newResults.crack_times_display;
    delete newResults.crack_times_seconds;
    delete newResults.guesses_log10;
    delete newResults.password;
    delete newResults.guesses;
    const out = Object.keys(newResults).map(function (key) {
      const value = newResults[key];
      return {key, value};
    });
    const allResults =  _.union(out, hashTimes, guesses);
    let orderedResults : any[] = [];
    allResults.forEach(function (result) {
      orderedResults[ITEM_ORDER.indexOf(result.key)] = result;
    });
    return orderedResults;
  }

  renderRow(rowData: any, sectionId: string, rowId: string) {
    let extraRowStyles = {};
    if (rowId === '0') {
      extraRowStyles = {
        borderTopWidth: 1,
        borderTopColor: '#333'
      };
    }

    return (
      <View style={[styles.listItem, extraRowStyles]}>
        <ResultItem data={rowData} />
      </View>
    );
  }

  render() {
    const results = this.parseData(zxcvbn(this.props.value));
    return (
      <View style={styles.container}>
        <ListView
          style={styles.listView}
          dataSource={this.dataSource.cloneWithRows(results)}
          renderRow={this.renderRow.bind(this)}
          removeClippedSubviews />
      </View>
    );
  }
}
