Panel = require './panel'

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

tr = $ '<tr>'; td = $ '<td>'
class GridPanel extends Panel
	@include Activateable

	events:
		'click .position-grid td': 'onCellClick'
		'click .colP':'addCols'
		'click .colM':'subCols'
		'click .rowP':'addRows'
		'click .rowM':'subRows'

	elements:
		'table.position-grid': 'grid'
		'.position-grid td':'cells'
		'.position-grid tr':'gridRows'

	activeCell: {}

	constructor: ->
		super

		@cols = @rows = 3
		@drawTable @cols, @rows

	onCellClick: (e) ->
		@activeCell =
			col: (target = $ e.target).index()
			row: target.parent().index()

		@activateCell target

	activateCell: (target) =>
		@cells.removeClass 'active'
		target.addClass 'active'

		x = target.offset().left - @offset.left + target.width()/2+1
		y = target.offset().top - @offset.top + target.height()/2+1

		x = Math.ceil(@maxX*x/@maxWidth)
		y = Math.ceil(@maxY*y/@maxHeight)
		@update {x, y, @reference}
		@change()

	deactivateCurentCell: =>
		@cells.removeClass 'active'

	updateSelf: (e, data={}) =>
		super and @deactivateCurentCell() if data.from isnt @

	drawTable: (cols, rows) ->
		@grid.html ''

		@rows = Math.max(1, Math.min(@rows, 10))
		@cols = Math.max(1, Math.min(@cols, 10))

		row = tr.clone()
		for i in [1..@cols]
			row.append td.clone()
		for i in [1..@rows]
			@grid.append row.clone()
		@refreshElements()

		if (target = @grid.find "tr:nth(#{@activeCell.row}) td:nth(#{@activeCell.col})").length
			@activateCell target

	addCols: => @drawTable ++@cols, @rows
	subCols: => @drawTable --@cols, @rows
	addRows: => @drawTable @cols, ++@rows
	subRows: => @drawTable @cols, --@rows

module.exports = GridPanel
