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

class Clock extends Controller
	className: 'clock'
	@include Activateable
	template: window.require 'core/views/date-time/clock'

	events:
		'click .date_time-current': 'toggleView'
		'change .clockpicker': 'stopPropagation'

	elements:
		'.clockpicker': 'picker'
		'.clockpicker input': 'pickrInput'
		'.date_time-footer' : 'footer'
		'.hh': 'hoursEl'
		'.mm': 'minutesEl'
		'.time-elements': 'tElem'

	hours: '00'
	minutes: '00'

	constructor: ->
		super
		@months = $.datepickr::l10n.months

		do @render

	render: =>
		super

	activate: =>
		Activateable.activate.apply @, arguments
		@picker.clockpicker
			clockUpdate: (prop, val) =>
				@[prop] = val
				@time = "#{@hours}:#{@minutes}"
				@hoursEl.text @hours
				@minutesEl.text @minutes
			afterDone: =>
				@el.trigger 'change', {@time}
			afterViewToggle: (view) =>
				@tElem.removeClass 'active'
				@["#{view}El"].addClass 'active'

	toggleView: =>
		@picker.clockpicker 'toggleView'

	update: (value) =>
		{@date, @time} = value
		[@hours, @minutes] = @time.split ':'
		@pickrInput.val @time

		[day, month, year] = @date.split '-'
		@footer.html "#{@months.longhand[month-1]} #{year}"

	stopPropagation: (e) ->
		e.stopPropagation()
		e.stopImmediatePropagation()

module.exports = Clock
