import Ember from "ember";
import KeyCodes from '../utilities/key-codes';

var focusOutEvent;

const VISIBLE = "visible";
const HIDDEN = "hidden";

function getNewHighlightIndex(direction, index, length) {
  if (direction === "down" && index < length - 1) {
    return index + 1;
  } else if (direction === "up" && index > 0) {
    return index - 1;
  }
  return index;
}

function keepHighlightInView(event) {
  var highlighted = document.getElementsByClassName("tt-cursor")[0];
  if (highlighted) {
    if (KeyCodes.keyPressed(event) === "downArrow") {
      highlighted.scrollIntoView(false);
    } else if (KeyCodes.keyPressed(event) === "upArrow") {
      highlighted.scrollIntoView();
    }
  }
}
export default Ember.Component.extend({
  layoutName: "components/auto-complete",
  highlightIndex: -1,
  visibility: HIDDEN,
  inputClass: '',
  inputClazz: Ember.computed(function () {
    return "typeahead text-input " + this.get('inputClass');
  }),
  keyUp: function (event) {
    if (KeyCodes.keyPressed(event) === "escape") {
      this.set("visibility", HIDDEN);
    } else if (!KeyCodes.isEscapedCode(event)) {
      this.set("highlightIndex", -1);
      this.get("options").forEach(function (item) {
        item.set("highlight", false);
      });
      this.set("visibility", VISIBLE);
      this.set("inputVal", Ember.$(event.target).val());
    }
    keepHighlightInView(event);
  },
  focusIn: function () {
    if (this.get("visibility") === HIDDEN) {
      this.set("visibility", VISIBLE);
    }
  },
  focusOut: function () {
    clearTimeout(focusOutEvent);
    var self = this;
    var func = function () {
      if (self.isDestroyed) {
        return;
      }
      self.set("visibility", HIDDEN);
      if (!self.get("selectedFromList") && !self.hasInputMatchingSuggestion()) {
        self.set("inputVal", "");
        self.set("selectedValue", "");
      }
    };
    focusOutEvent = Ember.run.later(this, func, 200);
  },
  keyDown: function (event) {
    if (this.get("visibility") !== HIDDEN) {
      if (KeyCodes.keyPressed(event) === "downArrow") {
        this.highlight("down");
      } else if (KeyCodes.keyPressed(event) === "upArrow") {
        this.highlight("up");
      } else if (KeyCodes.keyPressed(event) === "enter" || KeyCodes.keyPressed(event) === "tab") {
        if (!Ember.isBlank(this.selectableSuggestion)) {
          this.send("selectItem", this.selectableSuggestion);
          this.set("visibility", HIDDEN);
        } else if (this.hasInputMatchingSuggestion()) {
          this.set("selectedFromList", true);
          this.set("visibility", HIDDEN);
        }
      }
    } else {
      this.set("visibility", VISIBLE);
    }
  },

  onInput: Ember.observer('selectedValue', function() {
    var options = this.get("options");
    var input = this.getWithDefault("selectedValue", "");

    this.set("suggestions", this.determineSuggestions(options, input));
  }),

  highlight: function (direction) {
    var length = this.get("suggestions").length;
    var currentHighlight = this.get("highlightIndex");
    var nextHighlight = getNewHighlightIndex(direction, currentHighlight, length);

    if (currentHighlight >= 0) {
      this.get("suggestions").objectAt(currentHighlight).set("highlight", false);
    }

    var newSelectedItem = this.get("suggestions").objectAt(nextHighlight);
    newSelectedItem.set("highlight", true);
    this.set("selectableSuggestion", newSelectedItem);
    this.set("highlightIndex", nextHighlight);
  },
  hasInputMatchingSuggestion: function() {
    var suggestions = this.get('suggestions');
    var input = this.getWithDefault('selectedValue', '').toLowerCase();

    if (suggestions.length !== 1) { return false; }

    return input === suggestions[0].get(this.get('valueProperty')).toLowerCase();
  },
  actions: {
    selectItem: function (item) {
      var valueProperty = this.get("valueProperty");
      this.set("selectedFromList", true);
      this.set("selectedValue", item.get(valueProperty));

      this.sendAction('selectItem', item);
    }
  }
});

@@ -822,16 +822,48 @@
 HIDDEN,%0A
+  hideWhenNoSuggestions: false,%0A
   inputC
@@ -872,16 +872,16 @@
 ss: '',%0A
-
   inputC
@@ -1300,38 +1300,24 @@
 this.set
-(%22v
+V
 isib
-ility%22, VISIBLE
+le(
 );%0A     
@@ -1495,38 +1495,24 @@
 this.set
-(%22v
+V
 isib
-ility%22, VISIBLE
+le(
 );%0A    %7D
@@ -2653,30 +2653,16 @@
 .set
-(%22v
+V
 isib
-ility%22, VISIBLE
+le(
 );%0A 
@@ -3689,24 +3689,24 @@
 n false; %7D%0A%0A
-
     return i
@@ -3780,16 +3780,188 @@
 );%0A  %7D,%0A
+  setVisible()%7B%0A    let visible =  !this.get('hideWhenNoSuggestions') %7C%7C this.get('suggestions').length %3E 0;%0A    this.set('visibility', (visible ? VISIBLE : HIDDEN));%0A  %7D,%0A
   action

add hideWhenNoSuggestions option