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

	refs: [
		{
			ref: 'newGroupButton',
			selector: '#newGroupButton'
		},
		{
			ref: 'deleteGroupButton',
			selector: '#deleteGroupButton'
		},
		{
			ref: 'editRuleNewGroupButton',
			selector: '#editRuleNewGroupButton'
		},
		{
			ref: 'editRuleGroup',
			selector: '#editRuleGroup'
		},
		{
			autoCreate: true,
			ref: 'newGroupWindow',
			selector: '#newGroupWindow',
			xtype: 'newGroupWindowAlias'
		},
		{
			ref: 'newGroupName',
			selector: '#newGroupName'
		},
		{
			ref: 'newGroupConfirmButton',
			selector: '#newGroupConfirmButton'
		},
		{
			ref: 'newGroupCancelButton',
			selector: '#newGroupCancelButton'
		},
		{
			ref: 'treegrid',
			selector: '#treegrid'
		},
		{
			ref: 'editGroupConfirmButton',
			selector: '#editGroupConfirmButton'
		},
		{
			ref: 'editGroupButton',
			selector: '#editGroupButton'
		}
	],

	init: function(application) {
		//open window on new group button
		this.control({
		    '#newGroupButton': {
		        click: this.openCreateNew
		    },
			'#editGroupButton': {
				click: function() {
					this.getNewGroupWindow().show();
					this.getNewGroupWindow().setTitle('Edit group');
					this.getNewGroupName().setValue(this.tmp_selected[0].data.name);
					this.getNewGroupName().focus();
					this.getNewGroupConfirmButton().hide();
					this.getEditGroupConfirmButton().show();
					this.tmp_method = "EDIT";
					//console.log("Edit: " + this.tmp_selected[0].data.name);
				}
			},
			'#editGroupConfirmButton': {
				click: function() {
					this.editGroup();
				}
			},
		    '#editRuleNewGroupButton': {
		        click: this.openCreateNew
		    },
			'#treegrid': {
		        selectionchange: function(model, selected, eOpts) {
					this.tmp_selected = selected;
		        }
		    },
		//close window on cancel
		    '#newGroupCancelButton': {
		        click: function() {
		            this.getNewGroupWindow().destroy();
		        }
		    },
		//render confirm button active and inactive
		    '#newGroupName': {
		        change: function(component, newValue, oldValue) {
					if(newValue.length > 0 && this.isGroupNew(newValue)) {
						if(this.tmp_method === 'NEW') {
							this.getNewGroupConfirmButton().enable();
						}
						else if(this.tmp_method === 'EDIT') {
							this.getEditGroupConfirmButton().enable();
						}
					}
					else {
						this.getNewGroupConfirmButton().disable();
						this.getEditGroupConfirmButton().disable();
					}
		        },
				specialkey: function(field, e) {
					if (e.getKey() == e.ENTER) {
						if (this.tmp_method === 'NEW') {
							if(!this.getNewGroupConfirmButton().isDisabled())
								this.createGroup();
						} else if (this.tmp_method === 'EDIT') {
							if(!this.getEditGroupConfirmButton().isDisabled())
								this.editGroup();
						}
					}
				}
		    },
		//confirm new response
		    '#newGroupConfirmButton': {
		        click: function() {
		            this.createGroup();
		        }
		    },
		//delete group button
		    '#deleteGroupButton': {
		        click: function() {
		            this.deleteGroup();
		        }
		    },
			//Activate/Deactivate group
			'#activateGroupButton': {
				click: function(btn) {
					btn.disable();
					this.activateGroup();
				}
			},
			'#deactivateGroupButton': {
				click: function(btn) {
					btn.disable();
					this.deactivateGroup();
				}
			}
		});
	},

	openCreateNew: function(btn) {
		this.getNewGroupWindow().animateTarget = btn;
		this.getNewGroupWindow().show();
		this.tmp_method = "NEW";

		this.getNewGroupName().focus();

	},

	createGroup: function() {
		var params = Ext.Object.fromQueryString(document.location.search);
		params.func = 'NEW';
		params.group = this.getNewGroupName().getValue();
		params.ruletype = "crit_role";

		this.getNewGroupWindow().disable();

		Ext.Ajax.request({ //manual AJAX POST
			url: '../../service/sod_get_possible_group.php',
			method: 'POST',
			params: params,
			jsonData: Ext.JSON.encode(params),
			success: function(response, object){
				var newId = response.responseText;

				this.getTreegrid().getStore().load({ //reload tree works every time
					callback: function() {
						var newRecord = this.getTreegrid().getStore().getRootNode().findChild('id', newId);
						newRecord.expand();

						this.getNewGroupWindow().destroy(); //close create dialog

						this.getTreegrid().getSelectionModel().doSelect(newRecord);
					},
					scope: this
				});

				Ext.getStore('SelectGroupStore').load();

				//set new id as the choice in edit/create rule window
				if(this.getEditRuleGroup() !== undefined && this.getEditRuleGroup() !== null) {
					this.getEditRuleGroup().setValue(newId);
				}
			},
			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
				});
			},
			scope: this
		});
	},

	deleteGroup: function() {
		var group = this.getTreegrid().getSelectionModel().selected.getAt(0);

		if(group.hasChildNodes()) {
			Ext.Msg.alert(CCS.Translator.getText('Error deleting group {1} is not empty!', [group.data.name]));
		} else {
			var question = CCS.Translator.getText("Are you sure you want to delete {1}?", [group.data.name]);
			Ext.MessageBox.confirm(CCS.Translator.getText('Delete group'), question, function(btn){
				if(btn === 'yes'){
					group.data.ruleId = "Delete group";
					group.remove(false);
				}
			});
		}

	},

	activateGroup: function() {
		this.getTreegrid().setLoading(CCS.Translator.getText('Loading...'));

		var store = this.getTreegrid().getStore();
		store.suspendAutoSync();

		var group  = this.getTreegrid().getSelectionModel().getSelection()[0];

		var nochanges = true;
		group.eachChild(function(risk) {
			if(risk.get('statusId') != 'Active') {
				risk.set('ruleId', "Update rule");
				risk.set('statusId', 'Active');
				nochanges = false;
			}
		});

		var model = this.getTreegrid().getSelectionModel();
		store.resumeAutoSync();
		if(nochanges)
			this.getTreegrid().setLoading(false);

		store.sync({
			callback: function(){
				this.getTreegrid().setLoading(false);
				store.load({
					callback: function(records) {
						Ext.Array.each(records, function(rec){
							if(rec.get('id') == group.get('id'))
								model.doSelect(rec);
						});
					}
				});
			}, scope: this
		});
	},

	deactivateGroup: function() {
		this.getTreegrid().setLoading(CCS.Translator.getText('Loading...'));

		var store = this.getTreegrid().getStore();
		store.suspendAutoSync();

		var group  = this.getTreegrid().getSelectionModel().getSelection()[0];

		var nochanges = true;
		group.eachChild(function(risk) {
			if(risk.get('statusId') != 'Inactive') {
				risk.set('ruleId', "Update rule");
				risk.set('statusId', 'Inactive');
				nochanges = false;
			}
		});

		var model = this.getTreegrid().getSelectionModel();
		store.resumeAutoSync();
		if(nochanges)
			this.getTreegrid().setLoading(false);

		store.sync({
			callback: function(){
				this.getTreegrid().setLoading(false);
				store.load({
					callback: function(records) {
						Ext.Array.each(records, function(rec){
							if(rec.get('id') == group.get('id'))
								model.doSelect(rec);
						});
					}
				});
			}, scope: this
		});
	},

	editGroup: function() {
		var params = Ext.Object.fromQueryString(document.location.search);
		params.func = 'EDIT';
		params.group = this.getNewGroupName().getValue();
		params.ruletype = "sod_role2";
		//console.log(this.tmp_selected[0].data.id);
		params.id = this.tmp_selected[0].data.id;

		this.getNewGroupWindow().disable();

		Ext.Ajax.request({ //manual AJAX POST
			url: '../../service/sod_get_possible_group.php',
			method: 'POST',
			params: params,
			jsonData: Ext.JSON.encode(params),
			success: function(response, object){
				var newId = response.responseText;

				this.getTreegrid().getStore().load({ //reload tree works every time
					callback: function() {
						var newRecord = this.getTreegrid().getStore().getRootNode().findChild('id', newId);
						newRecord.expand();

						this.getNewGroupWindow().destroy(); //close create dialog

						this.getTreegrid().getSelectionModel().doSelect(newRecord);
					},
					scope: this
				});

				Ext.getStore('SelectGroupStore').load();

				//set new id as the choice in edit/create rule window
				if(this.getEditRuleGroup() !== undefined && this.getEditRuleGroup() !== null) {
					this.getEditRuleGroup().setValue(newId);
				}
			},
			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
				});
			},
			scope: this
		});
	},

	isGroupNew: function(name) {
		var exists = false;

		var groups = this.getTreegrid().getRootNode().childNodes;
		for(var key in groups) {
			if(groups[key].get('name').toLowerCase() == name.toLowerCase())
				exists = true;
		}

		return !exists;
	}

});
