 
   _prepareNewProduct: (product) ->
     Promise.all [
-      @_resolveProductTypeReference(product.productType?)
+      @_resolveReference(@client.productTypes, 'productType', product.productType?, "name=\"#{productTypeRef.id}\"")
       @_resolveProductCategories(product.categories?)
-      @_resolveTaxCategoryReference(product.taxCategory?)
+      @_resolveReference(@client.taxCategories, 'taxCategory', product.taxCategory?, "name=\"#{taxCategoryRef.id}\"")
     ]
     .spread(prodType, prodCats, taxCat) =>
       if not prodType.isRejected

  constructor: (@logger, options = {}) ->
    @sync = new ProductSync
    @client = new SphereClient options
    @_cache = {}

  _resetSummary: ->
    @_summary =

      if not taxCat.isRejected
        product.taxCategory = taxCat.value

  _resolveProductCategories: (cats) ->
    new Promise (resolve, reject) =>
      if _.isEmpty(cats)
        reject("Product categories are undefined.")
      else
        Promise.all cats.map(cat =>
          @_resolveReference(@client.categories, 'categories', cat, "externalId=\"#{cat.id}\""))
        .then (result) -> resolve(result)

  _resolveReference: (service, refKey, ref, predicate) ->
    new Promise (resolve, reject) =>
      if not ref
        reject("Missing #{refKey}")
      else if @_cache[refKey][ref.id]
        resolve(@_cache[refKey][ref.id])
      else
        service.where(predicate).fetch()
        .then (result) =>
          # Todo: Handle multiple response, currently taking first response.
          @_cache[refKey][ref.id] = result.body.results[0]
          resolve(result.body.results[0])

module.exports = ProductImport
