Ext.define("Portfolio.dynapp.util.Service", {
	singleton: true,

	base: {
		url: "/ip2-services/ip2DynApp.aspx",
		name: "Portfolio.dynapp.model.Detail"
	},

	alternateClassName: [
		"Ext.dynapp.util.Service"
	],

	getPath: function(o_value) {

		var i_self = this;
		var s_url = Portfolio.dynapp.util.Service.base.url;

		o_value = o_value || {};

		var a_path = [s_url];

		if (o_value.hasOwnProperty("library")) {
			a_path.push(o_value.library);
		}

		if (o_value.hasOwnProperty("file")) {
			a_path.push(o_value.file);
		}

		a_path.push("json");

		var s_result = a_path.join(".");

		return s_result;
	},

	getModelName: function(o_value) {

		var i_self = this;
		var s_return = Portfolio.dynapp.util.Service.base.name;

		if (o_value.library && o_value.file) {
			s_return = [o_value.library, o_value.file].join("-");
		}

		return s_return;
	},

	getMeta: function(o_value, f_callback) {

		Ext.Ajax.request({
			url: Portfolio.dynapp.util.Service.getPath(o_value),
			jsonData: {
				action: "getMeta"
			},
			success: function (response, request) {
				var result;
				try {
					result = Ext.decode(response.responseText);
				}
				catch (err) {
					result = {
						fields: [],
						properties: {},
						srcPlugin: ""
					};
				}
				var o_result = {
					fields: result.fields || [],
					id: "_id_",
					properties: result.properties || {},
					srcPlugin: ""
				};
				if (o_result.properties.plugin) {
					if (!Ext.isObject(o_result.properties.plugin)) {
						o_result.srcPlugin = o_result.properties.plugin;
						eval("o_result.properties.plugin =" + o_result.properties.plugin);
					}
					else {
						o_result.srcPlugin = o_result.properties.plugin.src || "{}";
						eval("o_result.properties.plugin =" + o_result.srcPlugin);
					}
					if (!o_result.properties.plugin.permissions) {
						o_result.properties.plugin.permissions = Ext.apply({}, {
							create: true,
							read: true,
							update: true,
							"delete": true
						});
					}
					else {
						var o_permissions = o_result.properties.plugin.permissions;
						Ext.applyIf(o_permissions, {
							create: true,
							read: true,
							update: true,
							"delete": true
						});
					}
				}
				else {
					o_result.properties.plugin = Ext.apply({}, {
						permissions: {
							create: true,
							read: true,
							update: true,
							"delete": true
						}
					});
				}

				Ext.Array.each(o_result.fields, function(o_field) {
					if (o_field.type) {
						o_field.dataType = o_field.type;
						delete o_field.type;
					}
				});

				f_callback(o_result);
			},
			failure: function() {
				var o_metaData = {
					fields: [],
					id: "_id_",
					properties: {
						plugin: {
							permissions: {
								read: true,
								create: true,
								update: true,
								"delete": true
							}
						}
					}
				};
				f_callback(o_metaData);
			}
		});
	}
});
