/*
 * File: app/controller/AddRemoveRoleController.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.AddRemoveRoleController', {
	extend: 'Ext.app.Controller',

	refs: [
		{
			ref: 'mainTreeGrid',
			selector: '#treegrid'
		},
		{
			ref: 'removeRoleButton',
			selector: '#removeRoleButton'
		},
		{
			ref: 'addRoleButton',
			selector: '#addRoleButton'
		},
		{
			autoCreate: true,
			ref: 'addRoleToRuleWindowClass',
			selector: '#addRoleToRuleWindow',
			xtype: 'addRoleToRuleWindowAlias'
		},
		{
			ref: 'addToRuleCancelButton',
			selector: '#addToRuleCancelButton'
		},
		{
			ref: 'addToRuleClearButton',
			selector: '#addToRuleClearButton'
		},
		{
			ref: 'addToRuleAddButton',
			selector: '#addToRuleAddButton'
		},
		{
			ref: 'addToRuleTreePanel',
			selector: '#addRoleToRuleTreePanel'
		},
		{
			ref: 'addToRuleSearchField',
			selector: '#addToRuleSearchField'
		}
	],

	init: function(application) {
		//main GUI buttons
		this.control({
		    '#removeRoleButton': {
		        click: function() {
		            this.removeRole();
		        }
		    }
		});
		this.control({
		    '#addRoleButton': {
		        click: function() {
		            this.getAddRoleToRuleWindowClass().show(); //open window
					this.getMainTreeGrid().getSelectionModel().selected.getAt(0).expand(); //expand selected rule on tree
					//add trigger listener on search trigger
		            var me = this;
		            this.getAddToRuleSearchField().onTriggerClick = function(event) {
		                me.search();
		            };
					//set params in search text and focus field
					this.getAddToRuleSearchField().setValue(this.getAddToRuleTreePanel().getStore().getProxy().extraParams.rolefilter);
		            this.getAddToRuleSearchField().focus();

					this.rule = this.getMainTreeGrid().getSelectionModel().selected.getAt(0);
		        }
		    }
		});
		//close window on cancel
		this.control({
		    '#addToRuleCancelButton': {
		        click: function() {
		            this.getAddRoleToRuleWindowClass().destroy();
		        }
		    }
		});
		//clear selection
		this.control({
		    '#addToRuleClearButton': {
		        click: function() {
		            this.getAddToRuleTreePanel().getSelectionModel().deselectAll();
		            this.getAddToRuleClearButton().blur();
		        }
		    }
		});
		//add selection
		this.control({
		    '#addToRuleAddButton': {
		        click: function() {
		            this.addSelection();
		        }
		    }
		});
		//search
		this.control({
		    '#addToRuleSearchField': {
		        specialkey: function(field, e) {
		            if (e.getKey() == e.ENTER) {
		                this.search();
		            }
		        }
		    }
		});

		//add listener to treegrid
		this.control({
		    '#addRoleToRuleTreePanel': {
		        selectionchange: function(model, selected, eOpts) {
		            this.selectionHasChanged(model, selected, eOpts);
		        }
		    }
		});
		//add doubleclick listener to view
		this.control({
			'#addRoleToRiskView': {
			beforeitemdblclick: function(dataview, record, index, e, eOpts) {
					var selectionmodel = dataview.getSelectionModel();
					if(selectionmodel.isSelected(record)) {
						selectionmodel.deselect(record);
						record.eachChild(function (n) {
							selectionmodel.deselect(n, true); //true in order to keep existing selections
						});
						record.collapse();
					} else {
						selectionmodel.select(record, true);
						record.eachChild(function (n) {
							selectionmodel.select(n, true); //true in order to keep existing selections
						});
						record.expand();
					}

					return false;    //return false in order to NOT to collapse tree on dblClick
				}
			}
		});

	},

	removeRole: function() {
		var node = this.getMainTreeGrid().getSelectionModel().selected.getAt(0);
		var role = node.data.name;
		var rule = node.parentNode.data.name;
		var question = CCS.Translator.getText("Are you sure you want to remove {1} from {2}?", [role, rule]);
		var store = this.getMainTreeGrid().getStore();
		Ext.MessageBox.confirm(CCS.Translator.getText('Remove role'), question, function(btn){
		    if(btn === 'yes'){

				store.suspendAutoSync();

		        node.set("ruleId", "remove");
		        node.set("origin", node.parentNode.data.id);
		        node.remove(false);

				store.resumeAutoSync();
				store.sync();
		    }
		});
	},

	addSelection: function() {
		this.getAddToRuleAddButton().blur();
		this.getAddToRuleAddButton().disable();
		this.getAddRoleToRuleWindowClass().disable();
		this.getMainTreeGrid().suspendLayouts();
		this.getMainTreeGrid().suspendLayout = false;

		var selection = this.getAddToRuleTreePanel().getSelectionModel().getSelection();
		this.getAddToRuleTreePanel().getSelectionModel().deselectAll();

		//var rule	= this.getMainTreeGrid().getSelectionModel().selected.getAt(0);
		var myModel	= this.getMainTreeGrid().getStore().model;

		var l = selection.length;

		this.portionSize = 15;
		this.portions = Math.floor(l / this.portionSize);
		this.rest = l-(this.portions * this.portionSize);
		this.newRecords = [];
		this.currentPortion = 0;

		for (var i = 0; i < l; i++) {
		    var newRecord = new myModel({
		        id: selection[i].data.roleid,
		        name: selection[i].data.technicalname,
		        response: selection[i].data.rolename,
		        ruleId: "add",
		        origin: this.rule.get('id'),
		        leaf: true,
				icon: selection[i].data.icon
		    });
			this.newRecords[i] = newRecord;
		}
		if(l > 20) {
			this.makePortion(this.rule);
		} else {
			this.addPortion(this.rule, this.newRecords, true);
		}
	},

	makePortion: function(rule) {
		var interval = (this.currentPortion < this.portions)?	(this.currentPortion*this.portionSize+1) + " - "+(this.currentPortion*this.portionSize+this.portionSize) :
																(this.portions*this.portionSize+1) + " - " + (this.portions*this.portionSize+this.rest);
		var portion = [];
		if(this.currentPortion < this.portions) {
			for(var i = 0; i < this.portionSize; i++) {
				portion[i] = this.newRecords[i+(this.currentPortion*this.portionSize)];
			}
			this.currentPortion++;
			var last = (this.rest === 0 && this.currentPortion == this.portions);
		} else {
			for(var i = this.portions*this.portionSize; i < (this.portions*this.portionSize)+this.rest; i++) {
				portion.push(this.newRecords[i]);
			}
			var last = true;
		}
		MyApp.app.message(CCS.Translator.getText('Adding roles to risk definition'), CCS.Translator.getText('Now adding {1} of the {2} selected roles', [interval, this.newRecords.length]));
		this.addPortion(rule, portion, last);
	},

	addPortion: function(rule, newRecords, last) {
		var store	= this.getMainTreeGrid().getStore();
		store.suspendAutoSync();

		var l = newRecords.length;
		for (var i = 0; i < l; i++) {
			rule.appendChild(newRecords[i]);
		}

		var scope = this;
		store.resumeAutoSync();
		if(last === true) {
			store.sync({
				callback: function() {
					MyApp.app.message(CCS.Translator.getText('Adding roles to risk definition'), CCS.Translator.getText('Done!'));
					delete(store.getProxy().extraParams.rule_id);
					store.load({
						callback: function() {
							scope.rule = scope.getMainTreeGrid().getStore().getById(rule.get('tree_id'));

							scope.getAddRoleToRuleWindowClass().enable();
							scope.getMainTreeGrid().suspendLayout = false;
							scope.getMainTreeGrid().resumeLayouts();
							scope.getMainTreeGrid().doLayout();
							scope.getMainTreeGrid().getSelectionModel().deselectAll();
							scope.getMainTreeGrid().getSelectionModel().doSelect(scope.rule);
						}
					});
				}
			});
		} else {
			store.sync({
				callback: function() {
					scope.makePortion(rule);
				}
			});
		}
	},

	search: function() {
		this.getAddToRuleTreePanel().getSelectionModel().deselectAll();
		var store = this.getAddToRuleTreePanel().getStore();
		var criteria = this.getAddToRuleSearchField().getValue();

		store.proxy.extraParams.rolefilter = criteria;
		store.load();
	},

	selectionHasChanged: function(model, selected, eOpts) {
		this.getAddToRuleClearButton().disable();
		this.getAddToRuleAddButton().disable();
		if(!Ext.isEmpty(selected)) {
		    this.getAddToRuleClearButton().enable();
		    this.getAddToRuleAddButton().enable();
		}
	}

});
