import Component from '@ember/component'
import { later, cancel } from '@ember/runloop'
import { computed, observer } from '@ember/object'
import { inject as service } from '@ember/service'

import layout from 'leaf-semantic-core/templates/components/leaf-toast'

ToastComponent = Component.extend(#SimpleAnimations,
  layout: layout

  tagName: 'section'
  classNames: ['toast', 'ui', 'transition', 'hidden']
  classNameBindings: ['typeClass']

  toasts: service('leaf-toasts')

  persistTime: 5000

  icon: computed('message', ->
    message = @get('message')
    return message.icon if message.icon
    switch message.type
      when 'info' then 'info circle'
      when 'success' then 'check circle outline'
      when 'warn' then 'exclamation triangle'
      when 'error' then 'bomb'
      else 'envelope outline'
  )

  typeClass: computed('message', ->
    type = @get('message.type')
    return('toast-' + type)
  )


  didInsertElement: ->
    @_super(arguments...)
    @$().transition('fly right')

  willInsertElement: ->
    @_super(arguments...)

    message = @get('message')

    if (message.status == 'passive' && !message.sticky)
      @set 'persistTimer', later(this, (->
        @set('persistTimer', null)
        @closeToast()
      ), @get('persistTime'))


  willDestroyElement: ->
    @_super(arguments...)

    if timer = @get('persistTimer')
      cancel(timer)
      @set('persistTimer', null)

  closeToast: ->
    @$().transition(
      animation: ('fly right')
      onComplete: => @toasts.closeToast(@get('message'))
    )

  actions:
    closeToast: ->
      @closeToast()
)

export default ToastComponent
