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

Composition			= window.require 'core/models/composition'
Widget 				= window.require 'core/models/widget'
User				= window.require 'core/models/user'

class Save extends Controller
	className 	: 'embedder'
	template 	: 'editor/views/embed'
	nextTitle 	: 'Publish'
	title 		: 'Done'

	@include Activateable

	elements:
		'.view-comp-btn': 'compBtn'
		'.ready-icon': 'readyIcon'

	events:
		'click .share-btn': 'notifyShareIntent'

	constructor: ->
		super
		@render()

	for: (@composition) ->
		return unless @composition.isPersisted()
		@widget or= Widget.find @composition.widget_id

	activate: ->
		return if @isActive()
		@$trigger 'viewChange', 'save'

		@publishComposition()
			.then(@for.bind @, @composition)
			.then(@_activate)
			.then @ready

	_activate: =>
		Activateable.activate.apply @, arguments

	ready: =>
		@delay $.fn.show.bind @readyIcon

	publishComposition: =>
		@composition
			.persist()
			.then((composition) =>
				@$trigger('composition:save', composition)
			).fail (e) =>
				console.warn("Persisting the composition failed. Saved as temporary.")
				@$trigger('composition:temporary:save', @composition)

	notifyShareIntent: (e) =>
		e.preventDefault()
		@$trigger 'sharew-intent', $(e.target).data 'target'

	onPopupClose: =>
		@$trigger 'Save:close', @pop = false if @pop

module.exports = Save
