Controller 		= window.require 'spine/controller'
Activateable	= window.require 'spine/controller/activateable'

Container = require("../../../core/services/container/instance").default;
UploadComponent = require('./upload.html').default

module.exports = class UploadBrowser extends Controller
  @include Activateable

  @isCompatible: (types) ->
    return false if !types
    return types.some (type) => type in ['audio', 'image', 'video']

  className: 'browser activateable upload-browser'
  attributes: authenticated: true
  title: 'uploads'

  constructor: (options) ->
    super
    @_initilized = new Promise((res) => @_resolve = res)

    { filetypes = [] } = options
    filetypes = filetypes.join(',')
    @options = Object.assign(options, { filetypes })

    @on 'activate', =>
      @_init() if !@component
      @component.activate()

  _init: ->
    @component = new UploadComponent target: @el[0], data: @options
    @component.on 'error', (ev) => @$trigger 'error', 'Error: ' + ev.message
    @component.on 'toggle', (event) => @trigger 'toggle', event
    @component.on 'clearContent', (event) => @trigger 'clearContent', event
    @component.observe 'loading', (loading) => @el.toggleClass('loading', loading)
    @_resolve()

  set: (state) ->
    @_initilized.then =>
      @component.set state

  observe: (args...)->
    @_initilized.then =>
      @component.observe args...
