Control 	= require './index'
Container 	= window.require 'spine/controller/container'
Spinner		= require './stepper'
Composition = window.require 'core/models/composition'

class Scale extends Control
	@include Container
	template  : 'core/views/scale'
	className : 'control-scale'

	elements:
		'.input-scale-width' : 'widthEl'
		'.input-scale-height': 'heightEl'
		'.input-scale-scaler' : 'scaleEl'
	events:
		'change:stepper':'updateValues'

	spinnerOptions: (attr) =>
		attribute: attr
		options:
			label: ''
			unit: ' px'
			min: parseInt(@options[attr]) * (parseInt(@options.min)/100)
			max: parseInt(@options[attr]) * (parseInt(@options.max)/100)
			default: @options[attr]

	constructor: ->
		super
		@getProp()

		@widthStepper  = new Spinner @spinnerOptions 'width'
		@heightStepper = new Spinner @spinnerOptions 'height'

		@scalerStepper  = new Spinner
			attribute: 'scale'
			options:
				label: ''
				unit: ' %'
				min: parseInt(@options.min)
				max: parseInt(@options.max)
				default: 100
		@steppers = [@widthStepper, @heightStepper, @scalerStepper]

	getProp: =>
		@dw = parseInt(@options.width)
		@dh = parseInt(@options.height)
		@ratio = @dw / @dh

	render: =>
		super
		for c in @steppers
			@[c.attribute+'El'].append c.render().el
		@

	updateValues: (e, o={}) =>
		e?.stopPropagation()
		@[o.attribute+'Updated'](o.val)

	widthUpdated: (w) => @updateSteppers w/@dw
	heightUpdated: (h) => @updateSteppers h/@dh
	scaleUpdated: (s) => @updateSteppers s/100
	updateSteppers: (scale, options) =>
		@height = @dh*scale
		@width = @dw*scale
		@scale = scale*100

		@change(options)

	change: (options) =>
		for c in @steppers
			c.change @[c.attribute], silent: true
		super {width: @width, height: @height}, options

	update : (item,type,options={})=>
		return if options.from and options.from is @
		@updateSteppers @item?[@attribute].width/@dw, silent:true

module.exports = Scale
