import _DB from './_DB.js';
import _Message from './_Message.js';
import _User from './_User.js';
import isArray from './util/isArray.js';

var _OpenOrders = {};

_OpenOrders.orders = [];

_OpenOrders.getOpenOrders = function(){
  return m.request({
    method: 'POST',
    url: '/cgi/listopenorders',
    body: {
      session_hash: _User.session_hash
      }
    })
  .then(function(res){
    if(res.success === true){
      if(!isArray(res.orders)){
        res.orders = [];
        }
      _OpenOrders.orders = res.orders;
      _OpenOrders.orders.forEach(function(order){
        order.user_id = _DB.integrate(order.user_id).id;
        _DB.integrate(order);
        });
      return _OpenOrders.orders;
      }
    else{
      res.errors.forEach(function(err){
        _Message.addError("Error getting open Orders: "+err);
        });
      }
    });
  };

_OpenOrders.loadOrder = function(order){
  return m.request({
    method: 'POST',
    url: '/cgi/loadorder',
    body: {
      session_hash: _User.session_hash,
      order_id: order.id
      }
    })
  .then(function(res){
    if(res.success === true){
      order = res.order;
      order.cart_id.lineitem_ids.forEach(function(lineitem){
        lineitem.item_id = _DB.integrate(lineitem.item_id).id;
        });
      _DB.integrateAllReturnIds(order.cart_id.lineitem_ids); // integrateAll modifies the Array in-place, so no need for '='
      order.cart_id = _DB.integrate(order.cart_id).id;
      order = _DB.integrate(res.order);
      
      return order;
      }
    else{
      res.errors.forEach(function(err){
        _Message.addError("Error loading Order #"+order.id+": "+err);
        });
      }
    });
  };

export default _OpenOrders;