
var RadioGroup = require('./radio-group');

module.exports = new Class({
	Extends: Htk.Field
	,Tag: 'htk-radio'
	,Properties: {
		tip: {
			type: String
			,set(x) {
				if (x)
					this.node.title = _(x);
			}
		},
		val: {
			type: String
			,get() {
				return this._val;
			}
			,set(x) {
				this._val = x;
				this.node.value = !x ? '' : x;
				this._onRadioGroupChange();
			}
		},
		name: {
			type: String
			,get() {
				return this.node.name;
			}
			,set(x) {
				this.node.name = x;
			}
		},
		radioGroup: {
			type: RadioGroup
			,get() {
				return this._radioGroup;
			}
			,set(x) {
				if (this._radioGroup)
					this._radioGroup.removeButton(this);

				this.link({_radioGroup: x}, {'changed': this._onRadioGroupChange});
				this.node.name = x.name;
				x.buttons.push(this);
				this._onRadioGroupChange();
			}
		}
	}
	
	,_radioGroup: null

	,render() {
		var radio = Vn.Browser.createRadio('', this.doc);
		radio.checked = false;
		radio.addEventListener('change', () => this._onChange());
		this._node = radio;
	}

	,_onChange() {
		if (this.node.checked && this._radioGroup)
			this._radioGroup.value = this._val || this.value;
	}
	
	,_onRadioGroupChange() {
		const value = this._radioGroup.value;
		this.node.checked =
			value && (value == this._val || value == this.value);
	}

	,putValue(value) {
		if (!value)
			this.node.value = '';
		else
			this.node.value = value;
	}

	,setEditable(editable) {
		this.node.disabled = !editable;
	}
});
