import _Item from './_Item.js';
import isArray from './util/isArray.js';

var ItemChooser = function(){
var search_term = '';
var results = [];
var chosen_item = null;
return {
view: function(vnode){
  var onchoose = vnode.attrs.onchoose;
  return m('.item-search', [
    m('input[type=text][placeholder=Model]', {
      onchange: function(e){
        search_term = e.target.value;
        results = [];
        if(search_term !== ''){
          _Item.searchByString(search_term)
            .then(function(res){
              if(res.success === true){
                if(isArray(res.results)){ // empty list comes back as `{}` from server instead of `[]`
                  results = res.results;
                  }
                else{
                  results = [];
                  }
                }
              });
            }
        },
      value: search_term
      }),
    m('table.table.table-striped.table-hover.results', [
      m('thead', [
        m('tr', [
          m('th', 'Brand'),
          m('th', 'Model'),
          m('th', 'Color')
          ])
        ]),
      m('tbody',
          results.map(function(item){
            var active_class = (chosen_item === item ? '.active' : '');
            return m('tr'+active_class, {
                onclick: function(e){
                  e.stopPropagation();
                  chosen_item = item;
                  onchoose(item);
                  }
                },[
              m('td', item.brand),
              m('td', item.model),
              m('td', item.color)
              ])
            })
          )
      ]
    )
  ]);
}
};
};

export default ItemChooser;