/*
 * File: app/controller/HistoryController.js
 *
 * This file was generated by Sencha Architect version 3.0.2.
 * http://www.sencha.com/products/architect/
 *
 * This file requires use of the Ext JS 4.2.x library, under independent license.
 * License of Sencha Architect does not include license for Ext JS 4.2.x. For more
 * details see http://www.sencha.com/license or contact license@sencha.com.
 *
 * This file will be auto-generated each and everytime you save your project.
 *
 * Do NOT hand edit this file.
 */

Ext.define('MyApp.controller.HistoryController', {
	extend: 'Ext.app.Controller',

	refs: [
		{
			autoCreate: true,
			ref: 'historyRuleWindow',
			selector: '#HistoryRule',
			xtype: 'HistoryRuleAlias'
		},
		{
			ref: 'viewRuleHistoryButton',
			selector: '#viewRuleHistoryButton'
		},
		{
			ref: 'historyRuleContainer',
			selector: '#HistoryRuleContainer'
		},
		{
			ref: 'historyRuleLabel',
			selector: '#HistoryRuleLabel'
		},
		{
			ref: 'mainTreeGrid',
			selector: '#treegrid'
		}
	],

	init: function(application) {
		this.control({
		    '#viewRuleHistoryButton': {
		        click: function() {
		            this.getHistoryRuleWindow().show();
					this.getHistoryRule();
		        }
		    }
		});
	},

	setUpWindowRule: function(data) {
		if (data && data.length && data.length > 0) {
			var fulltext = '';
			for(var i = 0; i < data.length; i++) {
				var user = data[i].user;
				var date = data[i].date;
				var text = data[i].text;
				var line = date + ', ' + user + ': '+text;

				if (i > 0) {
					fulltext += "\n";
				}
				fulltext += line;
			}
			this.getHistoryRuleLabel().setValue(fulltext);
		} else {
			this.getHistoryRuleLabel().setValue(CCS.Translator.getText('NO DATA!'));
		}
	},

	getHistoryRule: function() {
		var record = this.getMainTreeGrid().getSelectionModel().selected.getAt(0);
		var params = Ext.Object.fromQueryString(document.location.search);
		params.id = record.data.id;

		this.getHistoryRuleWindow().setTitle(CCS.Translator.getText('History log for risk ID {1}', [record.data.ruleId]));
		this.getHistoryRuleWindow().setLoading(CCS.Translator.getText('Loading...'));
		Ext.Ajax.request({
			url: '../../service/sod_get_history_rule.php',
			method: 'GET',
			params: params,
			success: function(response, object){
				var data = response.responseText;
				this.setUpWindowRule(Ext.JSON.decode(data));
				this.getHistoryRuleWindow().setLoading(false);
			},
			failure: function(response, object){
				var text = response.responseText;
				Ext.Error.raise({
					msg: 'Failed to get report parameters',
					option: text,   // whatever was passed into the method
					'object': object // other arbitrary info
				});
				this.getHistoryRuleWindow().setLoading(false);
			},
			scope: this
		});
	}

});
