PopupBase = require '../../controller/popup'

PixelPanel = require './pixel-panel'
GridPanel = require './grid-panel'
ReferencePanel = require './reference-panel'

class PositionPopup extends PopupBase
	template: require '../../views/pixelpanel'
	className: 'pixelPositionWrapper'

	elements:
		'.pixel-based': 'pixelPanel'
		'.grid-based' : 'gridPanel'
		'.reference-panel': 'referencePanelEl'

	events:
		'click .switch-positioning-type': 'toggleMode'
		'change': 'change'
		'click .currentPositionWrapper':'toggleReference'

	mods: ['pixel','grid']

	refreshGrids: =>
		@pixel.refresh()
		@grid.refresh()

	toggleMode: =>
		mod = @pixel.isActive()
		@[@mods[Number !mod]].deactivate()
		@[@mods[Number mod]].activate().refresh()

	toggleReference: =>
		mod = @referencePanel.isActive()
		@referencePanel[['activate', 'deactivate'][Number mod]]()

	release: ->
		@pixel.release()
		@grid.release()
		@referencePanel.release()
		super

	_createPopup: ->
		super.then =>
			@pixel.setDocument($(@popup.document))
			@refreshGrids()
			$(@popup.document.body).bind 'mouseenter', @pixel.mouseEnterBody

	render: ->
		super

		@referencePanel = new ReferencePanel el: @referencePanelEl
		@grid = new GridPanel el: @gridPanel
		(@pixel = new PixelPanel el: @pixelPanel, x: @x, y: @y).activate()

	update: =>
		@pixel.update arguments...
		@grid.update arguments...
		@referencePanel.update arguments...

	change: (ev, data) =>
		@trigger 'change', data

module.exports = PositionPopup
