Control 	= require '../index'
Container 	= window.require 'spine/controller/container'

Spinner		= require '../../controls/stepper'
Composition = window.require 'core/models/composition'

PanelsPopup = require './popup'

__ = $.extend.bind null, {}

class PositionControl extends Control
	@include Container
	template  : require '../../views/position'
	className : 'control-position'

	elements  :
		'.input-position-x .control' : 'xPos'
		'.input-position-y .control' : 'yPos'
		'.input-position-panel':'positionPanel'

	events:
		'click .input-position-panel':'showPixelPanel'
		'positionUpdate':'_change'

	constructor: (data) ->
		{@x, @y, @reference} = data.options.default

		super

		Composition.bind 'update', @compositionSizeUpdate
		@compositionSizeUpdate null, attribute: true

	getComposition: ->
		return @composition if @composition
		try
			composition = @item.composition()
		catch err
			console.error err
			return

	compositionSizeUpdate: (_, e) =>
		composition = @getComposition()
		return unless composition

		return unless e.attribute?
		mx = composition.width
		my = composition.height

		@panelsPopup.pixel.updatePanelSize mx, my
		@panelsPopup.grid.updatePanelSize mx, my

	render: =>
		super
		opts = __ @options, {label: '', help_text: ''}
		@_x = new Spinner el: @xPos, attribute: 'x', options: __ opts, default: @options.default.x
		@_y = new Spinner el: @yPos, attribute: 'y', options: __ opts, default: @options.default.y

		@listenTo @_x, 'change:stepper', @_change
		@listenTo @_y, 'change:stepper', @_change

		(@panelsPopup = new PanelsPopup {@x, @y, anchor: @positionPanel, options: @options}).render()
		@listenTo @panelsPopup, 'change', @_change

		@

	showPixelPanel: =>
		@panelsPopup.refreshGrids @panelsPopup.toggle()

	_change : (options) =>
		if options.attributes
			@[attr] = val for attr, val of options.attributes

		if options.attribute
			@[options.attribute] = options.value

		@change {@x, @y, @reference}

	update : (item,type,options={})=>
		opts = item[@attribute]
		{@x, @y, @reference} = opts
		@_x.update opts, type, options
		@_y.update opts, type, options
		@panelsPopup.update opts, type, options

	deactivate: =>
		@panelsPopup.hide()

	release: ->
		super
		@panelsPopup.release()

	setPopupCSS: (css) =>
		@panelsPopup.setPopupCSS css

	setPopupTargetWindow: (targetWindow) =>
		@panelsPopup.setPopupTargetWindow targetWindow

module.exports = PositionControl
