attr = DS.attr
App.Product = DS.Model.extend
  name: attr 'string'
  price: attr 'number'
  description: attr 'string'
  position: attr('number', defaultValue: 0)
  active: attr 'boolean', defaultValue: true
  image: attr()

  product_category: DS.belongsTo('product-category', async: false)
  product_orders: DS.hasMany('product-order', async: false)
  product_variants: DS.hasMany 'product-variant', async: false

  sorted_product_variants: Ember.computed 'product_variants.@each.name', 'product_variants.@each.position', ->
    @get('product_variants').sortBy('position')

  variantsDisplay: Ember.computed 'sorted_product_variants', ->
    @get('sorted_product_variants').mapBy('name').join(', ')

  addOrderItem: (options = {})->
    #if existing = @store.all('product_order').find((po)-> po.get('product') == product and not po.get('order'))
    if options.product_variant
      existing = @get('product_orders').find( (po)-> po.get('isNew') and po.get('product_variant') is options.product_variant )
    else
      existing = @get('product_orders').find( (po)-> po.get('isNew') )

    if existing
      existing.increment()
    else
      @store.createRecord 'product_order',
        product: this
        product_name: @get('name')
        price: @get('price')
        product_variant: options.product_variant
