import Mixin from '@ember/object/mixin'
import { alias } from '@ember/object/computed'
import { computed, observer } from '@ember/object'
import { once } from '@ember/runloop'



HasParent = Mixin.create(

  #
  #
  #
  mandatoryParent: false

  #
  #
  #
  parent: null

  #
  #
  #
  selectable: true


  #
  #
  #
  siblings: alias('parent.children')


  #
  # true if this child is currently selected.
  #
  # @property selected
  # @type Boolean
  #
  selected: computed('parent.selected',  ->
    @get('parent')?.isSelected(this)
  )

  #
  # The index of this tab in the `tab-list` component.
  #
  # @property index
  # @type Number
  #
  indexAsChild: computed('siblings.[]', ->
    if siblings = @get('siblings')
      siblings.indexOf(this)
  )

  #
  #
  #
  select: ->
    @get('parent')?.selectChild(this) if @get('selectable')


  #
  #
  #
  unselect:  ->
    @get('parent')?.unselect()


  #
  #
  #
  toggleSelect: ->
    if @get('selected')
      @unselect()
    else
      @select()

  #
  #
  #
  init: ->
    @_super(arguments...)
    once(this, @_registerWithParent)


  #
  #
  #
  willDestroyElement: ->
    @_super(arguments...)
    once(this, @_unregisterWithParent)


  _registerWithParent: ->
    if parent = @get('parent')

      if !@get('idx')
        console.debug('Children need an unique identifier idx, getting the elementId.')
        @set('idx', @get('elementId'))

      parent.registerChild(this)


    else if @mandatoryParent
      console.error "Missing mandatory parent. This subcomponent needs one."



  _unregisterWithParent: ->
    if parent = @get('parent')
      parent.unRegisterChild(this)

)

export default HasParent