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

define(
    [
	"aconf/dom",
	"aconf/statusbar",
	"aconf/widget/abstract/node",
	"jquery",
	"underscore"
    ],
    function(dom, statusBar, Base, $, _) {
	return Base.extend({
	    showStatus: true,

	    setStatus: function(status) {
		Base.setStatus.call(
		    this, status == "invalid" ? "invalid" : null
		);
	    },

	    render: function(data, meta) {
		this.dynamic = meta.members.dynamic;

		Base.render.call(this, data, meta);

		var table = $("<tbody>");
		this.el.append($("<table>").html(table));

		var self = this;

		_.each(meta.members.choice, function(choice) {
		    var selected = _.contains(data.data, choice.value);
		    if (!(choice.enabled || selected)) return;

		    var cbox = $("<input>").attr("type", "checkbox");
		    if (selected) cbox.attr("checked", "true");

		    var row = $("<tr>");
		    row.append($("<td>").html(cbox));

		    var item = $("<td>");
		    if (choice.ref)
			item.html(dom.objectRef(choice.ref)
				  .text(choice["ui-value"]));
		    else item.text(choice["ui-value"]);
		    row.append(item);

		    function setRowStatus() {
			dom.setStatus(row, data.status(choice.value));
		    }
		    setRowStatus();

		    cbox.change(function() {
			(
			    cbox.is(":checked") ?
				data.add(choice.value) :
				data.delete(choice.value)
			).done(function(txnValid) {
			    self.setStatus(data.status());
			    setRowStatus();
			    statusBar.validationReady(txnValid);
			});
		    });

		    table.append(row);
		});
	    }
	});
    }
);
