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

var _FrameAdmin = {};

_FrameAdmin.search_term = '';
_FrameAdmin.working_frames = [];
_FrameAdmin.results_frames = [];

_FrameAdmin.search_onchange_handler = function(e){
            _FrameAdmin.search_term = e.target.value;
            _FrameAdmin.results_frames = [];
            if(_FrameAdmin.search_term !== ''){
              //return _Item.searchByString(_FrameAdmin.search_term)
              return m.request({
                  method: 'POST',
                  url: '/cgi/framesbystring',
                  body: {
                    session_hash: _User.session_hash,
                    search_string: _FrameAdmin.search_term
                    }
                  })
                .then(function(res){
                  if(res.success === true){
                    if(isArray(res.results)){ // empty list comes back as `{}` from server instead of `[]`
                      _FrameAdmin.results_frames = res.results;
                      }
                    else{
                      _FrameAdmin.results_frames = [];
                      }
                    return _FrameAdmin.results_frames;
                    }
                  });
                }
            };

_FrameAdmin.add_button_onclick_handler = function(e){
  var loading_placeholder = {loading: true};
  loading_placeholder.index = _FrameAdmin.working_frames.push(loading_placeholder);
  return m.request({
    method: 'POST',
    url: '/cgi/createnewframe',
    body: {
      session_hash: _User.session_hash
      }
    }).then(function(res){
      if(res.success === true){
        _DB.integrate(res.new_frame);
        _FrameAdmin.working_frames[loading_placeholder.index] = res.new_frame;
        //_FrameAdmin.working_frames.push({idname: '', brand: '', model: '', color: '', color_description: '', description_short: '', size: '', material: '', price_silver: 0.00, price_gold: 0.00});
        }
      });
  };

_FrameAdmin.clear_button_onclick_handler = function(e){
  _FrameAdmin.working_frames = [];
  };

export default _FrameAdmin;