Controller = window.require 'spine/controller'

sum = (a, b) -> a+b
array_fill = (min, max) ->
	Array.apply(null, length: max-min).map sum.call, sum.bind null, min

class YearsController extends Controller
	className: 'years-view'
	template: window.require 'core/views/date-time/grid'
	table: window.require 'core/views/date-time/table'

	elements:
		'.date_time-wrapper table': 'tableEl'
		'.selected': 'selected'
		'.date_time-current':'title'

	events:
		'click .date_time-next': 'nextPage'
		'click .date_time-prev': 'prevPage'
		'click .date_time-cell': '_change'

	years: []

	constructor: ->
		super

		@index = @min

	render: ->
		super
		do @renderTable
		@el

	renderTable: ->
		@tableEl.html @table cols: 4, selected: @year, data: @years = array_fill @index, @index+16
		@refreshElements()
		@title.html "#{@index} - #{@index+16-1}"

	nextPage: =>
		@renderTable @index = Math.min @max-16, @index+16

	prevPage: =>
		@renderTable @index = Math.max @min, @index-16

	update: (date) =>
		{@year} = date

		@index = @year unless @year in @years
		do @renderTable

	_change: (e) =>
		@selected.removeClass('selected')
		(target = $ e.target).parent().addClass 'selected'
		year = target.text()

		@el.trigger 'change:year', {year} unless year is @year

module.exports = YearsController
