App.MenuProductComponent = Ember.Component.extend
  editMode: false
  code_filter: ''
  classNames: 'menu-product-container'
  classNameBindings: ['menu_product_class', 'editMode:editing', 'product.active:active:inactive']
  showProduct: (->
    return true unless filter = @get('code_filter')
    (@get('product.code') || "").toLowerCase().indexOf(filter.toLowerCase()) >= 0
  ).property('code_filter')
  menu_product_class: (-> "menu-product-#{@get('product.id') || 'new'}").property('product.id')
  code_filter_display: Ember.computed 'code_filter', 'product.code', ->
    return "&nbsp;".htmlSafe() unless code = @get('product.code')
    return code unless filter = @get('code_filter')
    index = code.toLowerCase().indexOf(filter.toLowerCase())
    if index >= 0
      pre_code = code.substring(0,index)
      highlight = code.substring(index,index + filter.length)
      post_code = code.substring(index + filter.length)
      "#{pre_code}<span class='highlight'>#{highlight}</span>#{post_code}".htmlSafe()
    else
      code
  actions:
    makeEditable: -> @set('editMode', true)
    save: ->
      return unless @get('product.isValid')
      @get('product.product_variants').forEach (product_variant)->
        product_variant.save() if product_variant.get('hasDirtyAttributes')
      if @get('product.hasDirtyAttributes')
        @get('product').save()
      @set 'editMode', false
    destroyProduct: (product)->
      if product.get('isNew')
        product.deleteRecord()
      else
        @modal 'confirm',
          model: product
          title_path: 'product.destroy_confirmation'
          ok: -> product.destroyRecord()
    rollbackProduct: ->
      if @get('product.isNew')
        @get('product').deleteRecord()
      else
        @get('product.product_variants').forEach (product_variant)->
          product_variant.rollbackAttributes()
        @get('product').rollbackAttributes()
      @set 'editMode', false
    addProductVariant: ->
      product_variant = @get('targetObject.store').createRecord('product_variant')
      @get('product.product_variants').addObject product_variant
    removeProductVariant: (product_variant)->
      product_variant.destroyRecord()
  didInsertElement: ->
    if @get('product.isNew')
      @set 'editMode', true
      Ember.run.later =>
        @$('input:first').focus()
      , 300
  namePlaceholder: (-> t "attributes.product.name").property()
  pricePlaceholder: (-> t "attributes.product.price").property()
  codePlaceholder: (-> t "attributes.product.code").property()
  descriptionPlaceholder: (-> t "attributes.product.description").property()
