import isUndefined from './util/isUndefined.js';
import _LineItem from './_LineItem.js';
import _Message from './_Message.js';
import _User from './_User.js';
import remove from './util/remove.js';
import removeByIndex from './util/removeByIndex.js';

var _Cart = {};

_Cart.updateQuantityOfItem = function(item, quantity){
  /*
  var possible_lineitem = _Cart.lineItemOfItem(item);  // _Cart.current.lineitems.find(function(lineitem){ return lineitem.item.id === item.id; });
  if(isUndefined(possible_lineitem)){
    possible_lineitem = _LineItem.createFromItem(item); 
    // possible_lineitem = _Cart.add(item);
    }
  possible_lineitem.quantity = quantity;
  */
  return m.request({
    method: 'POST',
    url: '/cgi/updateitemquantityincart',
    body: {
      session_hash: _User.session_hash,
      item_id: item.id,
      quantity: quantity
      }
    })
  .then(function(res){
    if(res.success === true){
      res.lineitems.forEach(function(lineitem, index){
        lineitem.item_id = _DB.integrate(lineitem.item_id).id // at first item_id has the actual object, which we integrate into _DB, but then we set it to the ID as is expected
        res.lineitems[index] = _DB.integrate(lineitem).id;
        });
      _Cart.current.lineitem_ids = res.lineitems; // at this point, res.lineitems contains only IDs
      }
    else{
      _Message.addError("There was an error adding to cart.");
      }
    });
  };
_Cart.removeLineItemOfItem = function(item){
  // TODO: do this on server-side, and return updated cart record with updated lineitem_ids
  remove(_Cart.current.lineitem_ids, function(lineitem_id){ return lineitem_id === item.id; });
  };
_Cart.removeLineItem = function(index){
  // TODO: do this on server-side, and return updated cart record with updated lineitem_ids
  removeByIndex(_Cart.current.lineitem_ids, index);
  };
_Cart.lineItemOfItem = function(item){
  if(_Cart.current !== null){
    return _DB.getRecord(  _Cart.current.lineitem_ids.find(function(lineitem_id){ return _DB.getRecord(lineitem_id).item_id === item.id; })  );
    }
  };

_Cart.placeOrder = function(){
  m.request({
    method: 'POST', 
    url: '/cgi/placeorder', 
    body: {
      session_hash: _User.session_hash
      }})
  .then(function(res){
    if(res.success){
      _Message.addNotification("Order #"+ res.order_id +" Received!");
      _Cart.current = res.new_cart_record;
      _Cart.current.lineitem_ids = [];
      _DB.integrate(_Cart.current)
      }
    });
  };

_Cart.current = null; //_Cart.new();

export default _Cart;