Controller   = window.require 'spine/controller'
Container    = window.require 'spine/controller/container'

WidgetEditor = require './editor'
RemotePreview = require './remote-preview'
Widget  = window.require 'core/models/widget'
Composition  = window.require 'core/models/composition'
Skin  = window.require 'core/models/skin'
Content = window.require 'core/models/content'

class Editor extends Controller
	@include Container
	@VERSION: '1.9.24'

	events:
		'SkinItem:selected': '_onSkinItemSelected'

	constructor: (options) ->
		if !options.remote then throw new Error('Remote UI.composition is missing!')
		if !options.premium then options.premium = false
		super

		@preview = new RemotePreview(@remote)
		@editor = new WidgetEditor({@premium})
		@append @editor
		$('html').toggleClass('isTouch', !!("undefined" != typeof document.documentElement.ontouchstart))

	hasPendingChange: -> @editor.hasPendingChange()

	initSave: -> @editor.initSave()

	new: (widget_id) ->
		@preview.startLoading()
		Widget.load(widget_id)
			.then(@_newComposition)
			.then(@_initialize)
			.then(=> @setOptions())
			.fail((e) -> console.error(e))

	edit: (composition_id) ->
		Composition.load(composition_id)
			.then(@_editComposition)
			.then(@_initialize)
			.then(=> @setOptions())
			.fail((e) -> console.error(e))

	step: -> @editor.step arguments...

	selectSkin: (skin) -> @editor.selectSkin(skin)

	_newComposition: (@widget) =>
		@composition = new Composition
			widget_id: @widget.id
			width: @widget.width
			height: @widget.height

		@composition.save({ajax:false})

	_editComposition: (@composition) =>
		@widget = @composition.getWidget()

	_initialize: =>
		@editor.for @composition
		@preview.load @composition

	_onSkinItemSelected: (ev, skin) =>
		@trigger('skin:select', skin)
		@preview.setSkin(skin)

	setInitOptions: (@initOptions) ->

	setOptions: (opts) -> @editor.setOptions $.extend step: 'skin', opts or @initOptions

	release: ->
		@_release @
		@preview.release()
		super

module.exports = Editor
