Control     = require '../text'
Container   = window.require 'spine/controller/container'

Popup = require './popup'

DateHelper = require './helper'

class DateTimeControl extends Control
	className: 'control control-date-time'
	template : window.require 'core/views/date-time/input'
	@include Container

	elements:
		'.input-icon': 'popupAnchor'

	events:
		'click .input-icon': 'toggle'
		'click .control-input': 'toggle'
		'focus .control-input': 'blur'

	_format: 'd-m-Y H:i'

	render: =>
		super
		(@popup = new Popup {anchor: @popupAnchor, @options}).render()
		@listenTo @popup, 'change', @change

	update: (item, type, options={}) =>
		@value = if item[@attribute]? then item[@attribute] else @options.default

		if @value
			@input.val DateHelper.format @options.format, new Date(@value)

		unless @value
			@value = +(DateHelper.format 'U', (new Date).getTime()) * 1000

		[date, time] = (DateHelper.format @_format, new Date(@value)).split ' '
		@popup?.update {date, time}

	change: (value) =>
		value = +(DateHelper.format 'U', value) * 1000
		super value

	toggle: =>
		return if (@_parent or= @parent())?.disabled

		@blur()
		do @popup.toggle

	blur: =>
		@input.blur()

	deactivate: =>
		@popup.hide()

	setPopupCSS: (css) =>
		@popup.setPopupCSS css

	setPopupTargetWindow: (targetWindow) =>
		@popup.setPopupTargetWindow targetWindow

module.exports = DateTimeControl
