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

define(
    [
	"aconf/dom",
	"aconf/error",
	"aconf/statusbar",
	"aconf/widget/abstract/base",
	"jquery",
	"underscore"
    ],
    function(dom, formatError, statusBar, Base, $, _) {
	return Base.extend({
	    init: function(
		data, name, meta, level, editable, removable
	    ) {
		this.editable = editable && meta.editable;

		var el = Base.init.call(
		    this,
		    data,
		    name,
		    meta,
		    level,
		    editable,
		    removable
		);

		if (this.editable)
		    this.field.change(_.bind(this.validateChange, this));

		return el;
	    },

	    staticRender: function(value, meta) {
		return $("<td>").text(value == null ? "" : value);
	    },

	    makeEl: function() {
		Base.makeEl.call(this);
		if (!this.field) this.field = this.el;
	    },

	    createEl: function() { return $("<input>"); },

	    render: function(value, meta) {
		this.field.attr({type: "text", value: value});
	    },

	    wrap: function() {
		var td = $("<td>");
		this.msg = $("<div>");
		td.append(this.msg);
		td.append(this.el);
		return td;
	    },

	    validate: function(value) {
		Base.validate.call(this, value);
		if (!this.visible || !this.editable) return;
		this.validateChange();
	    },

	    validateChange: function() {
		this.msg.text("[checking]");
		statusBar.setError("Validating changes", "validate");

		var self = this;

		this.data.set(this.name, this.get())
		    .done(function(txnValid) {
			self.msg.empty()
			self.updateStatus();
			statusBar.validationReady(txnValid);
			self.el.trigger("validated");

		    })
		    .fail(function(xhr) {
			dom.setText(self.msg, self.formatValidationError(xhr));
			self.setStatus("invalid");
			statusBar.validationReady(false);
		    });
	    },

	    get: function() {
		return this.editable ?
		    (this.field.val() || null) : this.data.get(this.name);
	    }
	});
    }
);
