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

MonthsController = require './months'
YearsController  = require './years'

class Calendar extends Controller
	className: 'calendar'
	@include Activateable
	template: 'core/views/date-time/calendar'

	elements:
		'.date-input':'input'
		'.datepickr-wrapper': 'calendarEl'
		'.date_time-content': 'content'
		'.date_time-footer' : 'footer'

	events:
		'click .datepickr-current-month': 'nextView'
		'click .date_time-current': 'nextView'
		'change:year': '_yearChanged'
		'change:month': '_monthChanged'
		'click .datepickr-next-month': 'triggerResize'
		'click .datepickr-prev-month': 'triggerResize'

	views: ['calendar', 'months', 'years']

	minYear: 1889
	maxYear: 2189

	constructor: ->
		super
		do @render
		@input.bind 'change', @_change

		@c = -1 #current view
		@l = @views.length
		do @nextView


	update: (value) ->
		{@date} = value
		[day, month, year] = @date.split '-'
		day=+day; month--; year=+year # convert to int, month is 0 indexed

		@datePickr.selectedDate = {day, month, year}
		[@datePickr.currentDayView, @datePickr.currentMonthView, @datePickr.currentYearView] = [day, month, year]
		do @datePickr.refresh

		@yearsController.update {year}
		@monthsController.update {year, month}

		[hours, minutes] = value.time.split ':'
		@footer.html "<span class=\"hh\">#{hours}</span>:<span class=\"mm\">#{minutes}</span>"

	render: ->
		super
		@datePickr = @input.datepickr(dateFormat: 'j-n-Y', firstDayOfWeek: 1)[0]

		@content.append (@monthsController = new MonthsController {@minYear, @maxYear}).el
		@content.append (@yearsController  = new YearsController min: @minYear, max: @maxYear).el

		@refreshElements()

	_change: =>
		@el.trigger 'change', {date} unless (date = @input.val()) is @date

	_monthChanged: (ev, data) =>
		date = @date.replace /-\d+-\d+$/, "-#{data.month+1}-#{data.year}"
		@el.trigger 'change', {date}
		@view 'calendar'

	_yearChanged: (ev, data) =>
		date = @date.replace /\d+$/, data.year
		@el.trigger 'change', {date}
		@view 'months'

	nextView: =>
		@view @views[(@c+1)%@l] #loop through all views

	view: (view) =>
		@content.children().hide()
		@c = @views.indexOf view
		do @[view]
		do @triggerResize

	calendar: =>
		@calendarEl.show()

	months: =>
		@monthsController.render().show()

	years: =>
		@yearsController.render().show()

	triggerResize: =>
		@el.trigger 'resize:popup'

module.exports = Calendar
