URL = require './url'

class Audio extends URL
	className : 'control-audio'
	template  : 'core/views/audio'
	elements  : 'input': 'input'
	type      : 'audio'

	elements:
		'.url-thumb': 'toggleBtn'

	events:
		'click .play-btn,.pause-btn': 'toggle'
	
	constructor: ->
		super
		@deflt =
			volume:   100
			onpause:  @status
			onresume: @status
			onfinish: @status
			onplay:   @status

	render: ->
		super
		@toggleBtn.toggle soundManager?
		@delay =>@update(@item)
		@

	update: (item,t,options={}) =>
		@input.val @lastURL = (item[@attribute] or '')
		@onURL true, silent: true

	onInput: (e) ->
		super
		@sound?.destruct()
		@status()

	toggle: -> @sound?.togglePause()

	status: => @el.toggleClass 'playing', !@sound?.paused and @sound?.playState is 1

	onURL: (exists) =>
		super
		if soundManager? and exists and @lastURL?.length
			doit = => @sound = soundManager.createSound($.extend {url:@lastURL}, @deflt) or null
			if soundManager.enabled then doit() else soundManager.onready doit
		
		if exists and not @item[@attribute]
			@$removeClass('valid')
		
		@

	release: -> super?.sound?.destruct()

module.exports = Audio