console = window.require 'spine/utils/console'

Skin  		= window.require 'core/models/skin'
Content     = window.require 'core/models/content'

Events      = window.require 'spine/core/events'
Module      = window.require 'spine/core/module'

class RemotePreview extends Module
	@include Events

	constructor: (@remote) ->
		@style = $ '<style type="text/css">'
		super
		@currentWidget = @remote.getPreview().widget()
		@_loadDependencies()

	load: (@composition) =>
		@stopListening Content, 'create', @removeDemoContent
		@stopListening Content, 'create', @addContent

		unless @composition.getContent().length
			@listenTo Content, 'create', @removeDemoContent

		@listenTo Content, 'create', @addContent

		@listenTo @composition, 'update', @resize
		@setSkin @lastSkin if @lastSkin
		@trigger 'initialized'
		@

	resize: (composition) =>
		@currentWidget.resize()

	addContent: (item) =>
		return if item.composition_id isnt @composition.id
		console.group('Preview:addContent')
		@currentWidget.addContent item
		console.groupEnd('Preview:addContent')

	removeDemoContent: (item) =>
		return if item.composition_id isnt @composition.id
		console.group('Preview:removeDemoContent')
		@currentWidget.clearContent()
		@stopListening Content, 'create', @removeDemoContent
		console.groupEnd('Preview:removeDemoContent')

	setSkin: (@lastSkin) ->
		@currentWidget.setSkin @lastSkin

	_loadDependencies: ->
		if @remote.window.SoundManager?
			sm = new @remote.window.SoundManager
		if @remote.window.soundManager?
			sm = @remote.window.soundManager
		if sm
			window.soundManager = sm
			sm.setup @remote.window.soundManager.setup()

		if !window.videojs
			window.videojs = @remote.window.videojs

	release: =>
		@trigger 'release', @
		@unbind()
		@stopListening()

module.exports  = RemotePreview
