/*jslint laxbreak:true */
/*jslint laxcomma:true */
/*jslint loopfunc:true */
/*jslint strict:true */
/*jslint browser:true */
/*jslint devel:true */

define([
	"underscore"
	, "backbone"

	, "models/client"
]
, function (_, Backbone, Client) {
	"use strict";

	var Model	= Backbone.Model.extend({
		client:			null
		, idAttribute:	"hostname"

		, initialize:		function (attributes, options) {
			_.bindAll(this, "destroy", "getName", "relayEvent");
			var that		= this
			;

			this.client		= new Client(attributes);

			this.client.on("inited", function __fnServerModelClientInitedEvent(serverInfo) {
				if (serverInfo && serverInfo.get("dmap_itemname")) {
					that.set(_.extend({}, that.attributes, {name: serverInfo.get("dmap_itemname")}));
					// We could save here, but it is debatable if we want to leep the name attribute locally
					// that.save();
				}

				//that.client.fetchDatabases(that.client.fetchDatabase);
			});

			//this.client.on("all", this.relayEvent);

			return Model.__super__.initialize.call(this, arguments);
		}
/*
		, relayEvent:		function () {
			var eventName	=  arguments[0]
			;
			delete arguments[0];
console.log(eventName);
			this.trigger("client:" + eventName, _.values(arguments));
		}
 */
		, destroy:			function () {
			if (this.client && this.client.deinit) {
				this.client.deinit();
			}

			return Model.__super__.destroy.call(this, arguments);
		}

		, getName:			function () {
			if (this.get("name")) {
				return this.get("name");
			} else if (this.client && this.client.urlHost) {
				return this.client.urlHost();
			} else {
				return this.get("hostname");
			}
		}
	});

	return Model;
});