import SearchMulti from './SearchMulti';
import SymbolAutocomplete from './SymbolAutocomplete';
import findIndex from 'lodash/findIndex';
import {fetchJsonp} from 'services/fetch';
import filter from 'lodash/filter';
import map from 'lodash/map';
import React from 'react';

export const ErrorTypes = {
  // Some symbols passed to us via paste/csv were not found in the data api.
  INVALID_SYMBOLS: Symbol('Invalid Symbols passed'),
  // Could not connect to the data api (or was unable to parse the JSON from the api?).
  UNABLE_TO_CONNECT: Symbol('Unable to connect to server'),
  // Too many symbols were added
  TOO_MANY_SYMBOLS: Symbol('Too many symbols imported')
};

class SymbolAutocompleteMulti extends React.Component {
  constructor(props) {
    super(props);
  }

  parseQuotes(json) {
    const symbolsToAdd = [];
    const errors = [];
    for (const key in json) {
      const quote = json[key];
      if (!quote.hasOwnProperty('error')) {
        symbolsToAdd.push({
          label: quote.symbol + ' | ' + quote.name,
          value: quote.symbol,
          heading: 'Symbol (' + quote.exchange + ')',
          type: 'symbol'
        });
      } else {
        errors.push(key);
      }
    }
    if (symbolsToAdd.length !== 0) {
      const uniqueSymbols = filter(symbolsToAdd, (symbol) => findIndex(this.props.symbols, {value: symbol.value, type: 'symbol'}) === -1);
      this.props.onAddMultiSymbol(uniqueSymbols, this.props.symbols.length);
    }
    if (errors.length !== 0 && this.props.onError) {
      this.props.onError(ErrorTypes.INVALID_SYMBOLS, errors);
    }
  }

  searchSymbolArray(symbolArray) {
    let usymbolArray = map(symbolArray, (str) => str.toUpperCase());
    if (usymbolArray.length) {
      if (usymbolArray.length > 500) {
        this.props.onError(ErrorTypes.TOO_MANY_SYMBOLS, 'Too many symbols. Max 500. '  + (usymbolArray.length - 500) + ' ignored.');
        usymbolArray = usymbolArray.slice(0, 500);
      }
      const queryString = usymbolArray.join();
      return fetchJsonp('https://data.benzinga.com/rest/v2/quote?symbols=' + queryString, {timeout: 30000})
        .then(req => req.json())
        .then(json => this.parseQuotes(json))
        .catch(err => this.props.onError(ErrorTypes.UNABLE_TO_CONNECT, err));
    }
  }

  render() {
    const {onError, symbols, onAddSymbol, onAddMultiSymbol, onRemoveSymbol, ...childProps} = this.props;

    return (
      <SearchMulti
        {...childProps}
        completionKeys={['Enter', ',']}
        onAddTag={this.props.onAddSymbol}
        onAddMultiTag={(arr) => this.searchSymbolArray(arr)}
        onRemoveTag={this.props.onRemoveSymbol}
        tags={this.props.symbols}
        completions={[]}
        searchClass={SymbolAutocomplete}
        ignoreList={filter(map(this.props.symbols, (symbol) => symbol.type === 'symbol' && symbol.value), (val) => val)}
      />
    );
        // onChange={(e, value) => this.searchChange(e, value)}
  }
}
SymbolAutocompleteMulti.propTypes = {
  /**
   * function(object symbol, int index)
   *   Fired when the user adds a symbol.
   *   The autocomplete list is cleared whenever it is fired.
   *   symbol is taken directly from autocomplete so it is guaranteed to be in our data api.
   *   index is where in the list to insert the symbol.
  */
  onAddSymbol: React.PropTypes.func,
  /**
   * function(array symbols, int index)
   *   Fired when the user adds a list of symbols via pasting or csv file.
   *   the symbols are checked with the data api to make sure they are valid.
   *   index is where in the list to insert the symbol.
  */
  onAddMultiSymbol: React.PropTypes.func,
  /**
   * function(object symbol, int index)
   *   Fired when the user deletes a symbol from the list.
   *   symbol is the object as found in props.symbols.
   *   index is the location of the symbol in props.symbols.
  */
  onRemoveSymbol: React.PropTypes.func,
  /**
   * function(ErrorTypes errType, any error)
   *   Fired when an error occurs.
   *   errType is a Symbol found in ErrorTypes.
   *   error is either an array of strings if the error was invalid symbols
   *     or whatever object fetchJsonp/toJson thows on an error.
  */
  onError: React.PropTypes.func,
  /**
   * Any object that can be enumerated. Most likely an array or an Immutable.List.
   *   The list of symbols this helps to build.
  */
  symbols: React.PropTypes.any.isRequired,
};
SymbolAutocompleteMulti.defaultProps = {
  onAddMultiSymbol(data, index) {}
};
export default SymbolAutocompleteMulti;
