require('./style.scss');
var Calendar = require('../calendar');

module.exports = new Class({
	Extends: Htk.Field
	,Tag: 'htk-date-chooser'

	,format: _('%a, %e %b %Y')
	,calendar: null
	,ignoreCalendarChange: false
	
	,render() {
		const node = this.createRoot('button');
		node.classList.add('input');
		node.addEventListener('click', this._onClick.bind(this));

		this.label = this.createElement('span');
		node.appendChild(this.label);

		const dropDown = new Htk.Icon({
			name: 'expand_more'
		});
		node.appendChild(dropDown.node);

		this.setEditable(this._editable);
	}

	,putValue(value) {
		var dateString;

		if (value instanceof Date)
			dateString = Vn.Date.strftime(value, this.format);
		else
			dateString = '';

		Vn.Node.setText(this.label, dateString);
	}

	,setEditable(editable) {
		if (this.calendar) {		
			this.calendar.disconnectByInstance(this);
			this.calendar = null;
		}
		if (editable) {
			this.calendar = new Calendar();
			this.calendar.on('changed', this._onCalendarChange.bind(this));
			
			this.popup = new Htk.Popup();
			this.popup.child = this.calendar;
		}
	}

	,_onCalendarChange(calendar) {
		if (this.ignoreCalendarChange)
			return;
	
		this.popup.hide();
		
		var newDate = calendar.value;
		this.putValue(newDate);
		this.valueChanged(newDate);
	}

	,_onClick() {
		this.ignoreCalendarChange = true;
		this.calendar.value = this._value;
		this.calendar.goToSelectedMonth();
		this.ignoreCalendarChange = false;

		this.popup.show(this.node);
	}
});

