/*
 * Copyright (c) 2012-2014 Kaarle Ritvanen
 * See LICENSE file for license details
 */

define(["aconf/widget/field", "jquery", "underscore"], function(Base, $, _) {
    return Base.extend({
	createEl: function() { return $("<select>"); },

	staticRender: function(value, meta) {
	    return Base.staticRender.call(
		this,
		value ? _.findWhere(
		    meta.choice, {value: value}
		)["ui-value"] : "",
		meta
	    );
	},

	render: function(value, meta) {
	    var el = this.field.empty();

	    function opt(value, ui_value, selected) {
		var option = $("<option>").attr("value", value).text(ui_value);
		if (selected) option.attr("selected", "true");
		el.append(option);
	    }

	    if (!meta.required) opt("", "(none)", value == null);

	    _.each(
		meta.choice,
		function(choice) {
		    var selected = value == choice.value;
		    if (choice.enabled || selected)
			opt(choice.value, choice["ui-value"], selected);
		}
	    );
	}
    });
});
