Ext.define("Ext.ux.history.controller.History", {
	extend: "Ext.app.ViewController",

	alias: "controller.history",

	getEntityTitle: function(entityName) {

		var i_self = this;
		var i_controller = i_self.getController();

		i_controller.language = ip2.getUserLanguageCode();

		var i_entity = i_controller.getDmdEntityByEntityName(entityName);
		if (i_entity == null) {
			return entityName;
		}

		var s_title = i_entity.title[i_controller.language];

		if (s_title == undefined || s_title.length == 0) {
			s_title = i_entity.title.da;
		}

		if (s_title == undefined || s_title.length == 0) {
			s_title = value;
		}

		return s_title;
	},

	getXpdCollectionByEntityName: function(entityName, fieldName) {

		var i_controller = this;

		if (!i_controller.dmd) {
			i_controller.dmd = ip2.resource.baseConfig.dmd;
		}
		if (!i_controller.xpd) {
			i_controller.xpd = ip2.resource.baseConfig.xpd;
		}

		var i_entity = i_controller.getDmdEntityByEntityName(entityName);
		if (i_entity == null) {
			return null;
		}

		var s_collectionName = (i_entity.columns && i_entity.columns[fieldName]) ? i_entity.columns[fieldName].xpd : '';
		if (s_collectionName == undefined || s_collectionName.length == 0) {
			return null;
		}

		if (i_controller.xpd == undefined && i_controller.xpd_m == undefined) {
			return null;
		}

		return (i_controller.xpd) ? i_controller.xpd[s_collectionName] : i_controller.xpd_m[s_collectionName];
	},

	getDmdEntityByEntityName: function(s_entity) {

		var i_controller = this;
		var s_modelName = '';
		var o_entity;

		if (s_entity) {
			var o_dmds = ip2.resource.baseConfig.dmd || {};

			Ext.Object.each(o_dmds, function(s_key, o_value) {

				var o_model = o_value.model || {};
				var a_entities = o_model.entities || [];

				var o_entity = Ext.Array.findBy(a_entities, function(o_value) {
					return o_value.name == s_entity;
				});

				if (o_entity) {
					o_entity.dmd = o_value._path;
					return false;
				}
			});

			if (!o_entity) {

				var o_config = ip2.sajax.request({
					url: "ip2-services/entity2dmd.aspx?entity=" + s_entity,
					asJson: true
				});

				var o_dmd = ip2.resource.get(o_config.name);
				var o_model = o_dmd.model;
				var a_entities = o_model.entities;

				o_entity = Ext.Array.findBy(a_entities, function(o_value) {
					return o_value.name == s_entity;
				});

				o_entity.dmd = o_config.name;
			}
		}

		return o_entity;
	},

	formatTimestamp: function(ts) {

		var i_controller = this;
		i_controller.rules = ip2.getUiTypes();

		return i_controller.rules.isotimestamp.grid.renderer(ts);
	}
});
