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

	refs: [
		{
			ref: 'emptyContainer',
			selector: '#emptyContainer'
		},
		{
			autoCreate: true,
			ref: 'restriction',
			selector: '#Restriction',
			xtype: 'Restriction'
		},
		{
			ref: 'restrictionForm',
			selector: '#restrictionForm'
		},
		{
			ref: 'btnSave',
			selector: '#btnSave'
		},
		{
			ref: 'fieldScopeLabel',
			selector: '#fieldScopeLabel'
		}
	],

	init: function(application) {
		this.control({
			'#btnCreate': {
				click: this.openCreate
			},
			'#btnSave': {
				click: this.create
			},
			'#fieldScope': {
				select: this.setLabel,
				change: this.checkForm
			},
			'#typeCombo': {
				select: this.setupForm,
				change: this.checkForm
			},
			'#fieldField': {
				select: this.checkForm,
				change: this.checkForm
			},
			'#fieldLow': {
				change: function(comp, newValue, oldValue) {
					if(newValue !== oldValue) {
						comp.setValue(newValue.toUpperCase());
						this.checkForm();
					}
				}
			},
			'#fieldHigh': {
				change: function(comp, newValue, oldValue) {
					if(newValue !== oldValue) {
						comp.setValue(newValue.toUpperCase());
						this.checkForm();
					}
				}
			}
		});
	},

	openCreate: function(btn) {
		btn.blur();
		this.getRestriction().animateTarget = btn;
		this.getRestriction().show();

		var params = MyApp.app.getController('Content').params;

		var scope = this.getRestrictionForm().getForm().findField('scope');
		if(params.project === true) {
			scope.select(3);
		}
		else if(params.local === true) {
			scope.select(2);
		}
		else if(params.global === true) {
			scope.select(1);
		}
		else {
			scope.select(2);
		}

		this.setLabel(scope, [scope.getStore().getById(scope.getValue())]);
		this.setupForm();

		var me = this;
		setTimeout(function() {
			me.getRestrictionForm().getForm().findField('type').expand();
		}, 500);
	},

	setLabel: function(component, selection) {
		if(selection.length > 0) {
			var params = MyApp.app.getController('Content').params;
			switch(selection[0].get('id')) {
				case 1:
					this.getFieldScopeLabel().setText('');
				break;
				case 2:
					this.getFieldScopeLabel().setText(params.system +'/'+ params.client);
				break;
				case 3:
					this.getFieldScopeLabel().setText(params.projectName);
				break;
			}
		}
		this.checkForm();
	},

	setupForm: function() {
		/* depending on type selection the form will change */

		//disable all fields
		var formFields = this.getRestrictionForm().items.items;
		for(var x in formFields) {
			var field = this.getRestrictionForm().getForm().findField(formFields[x].name);
			if(!Ext.isEmpty(field)) {
				field.disable();
			}
		}
		//enable type and scope fields
		this.getRestrictionForm().getForm().findField('scope').enable();
		this.getRestrictionForm().getForm().findField('type').enable();
		this.getRestrictionForm().getForm().findField('comment').enable();

		this.getRestrictionForm().getForm().findField('low').hide();
		this.getRestrictionForm().getForm().findField('high').hide();
		this.getRestrictionForm().getForm().findField('field').show();

		//enable field relevant to the type
		var focusField = this.getRestrictionForm().getForm().findField('type');

		var type = this.getRestrictionForm().getForm().findField('type').getValue();
		switch(type) {
			case 1:
				focusField = this.getRestrictionForm().getForm().findField('field');
				focusField.setFieldLabel(CCS.Translator.getText('Org Level'));
				this.getSapData('orglvl');
			break;
			case 2:
				focusField = this.getRestrictionForm().getForm().findField('field');
				focusField.setFieldLabel(CCS.Translator.getText('Object Class'));
				this.getSapData('objclass');
			break;
			case 3:
				focusField = this.getRestrictionForm().getForm().findField('field');
				focusField.setFieldLabel(CCS.Translator.getText('Object'));
				this.getSapData('object');
			break;
			case 4:
				focusField = this.getRestrictionForm().getForm().findField('field');
				focusField.setFieldLabel(CCS.Translator.getText('Field'));
				this.getSapData('field');
			break;
			case 5:
				this.getRestrictionForm().getForm().findField('field').hide();
				this.getRestrictionForm().getForm().findField('low').enable();
				this.getRestrictionForm().getForm().findField('high').enable();
				this.getRestrictionForm().getForm().findField('low').show();
				this.getRestrictionForm().getForm().findField('high').show();
				focusField = this.getRestrictionForm().getForm().findField('low');
			break;
		}

		focusField.enable();
		setTimeout(function() {
			focusField.focus();
		}, 150);
		this.checkForm();
	},

	checkForm: function() {
		this.getBtnSave().disable();
		var value;

		var type = this.getRestrictionForm().getForm().findField('type').getValue();
		switch(type) {
			case 1:
			case 2:
			case 3:
			case 4:
				value = this.getRestrictionForm().getForm().findField('field').getValue();
			break;
			case 5:
				value = this.getRestrictionForm().getForm().findField('low').getValue();
			break;
		}

		if(!Ext.isEmpty(value))
			this.getBtnSave().enable();

	},

	getSapData: function(type) {
		this.getRestriction().setLoading(true);

		var org_params = MyApp.app.getController('Content').params;

		//create sapevent url
		var url = "SAPEVENT:TCR_CRE";

		var params = {
			guiid		: org_params.guiid,
			type		: type,
			system		: org_params.system,
			client		: org_params.client,
			rfctarget	: org_params.system+"_"+org_params.client
		};
		var par = Ext.Object.toQueryString(params);
		//open sapevent in a hidden container
		this.getEmptyContainer().update('<iframe src="'+url+"?"+par+'" width="100%" height="100%" frameborder="0" style="border-color: white;"></iframe>');

		var me = this;
		setTimeout( function() {
			me.ping({
				guiid	: org_params.guiid,
				type	: type
			});
		}, 750);
	},

	ping: function(params) {
		var me = this;
		Ext.Ajax.request({ //manual AJAX
			url: '../../service/ping.php',
			method: 'GET',
			params: params,
			success: function(response, object){
				var data = Ext.JSON.decode(response.responseText);
				if(data.result) {
					var field = this.getRestrictionForm().getForm().findField('field');
					var store = field.getStore();

					store.proxy.extraParams = params;
					store.load({callback: function(records) {
						field.enable();
						if(records.length > 0)
							field.select(records[0]);
						field.expand();
					}, scope: this});

					this.getRestriction().setLoading(false);
				}
				else {
					setTimeout( function() {
						me.ping(params);
					}, 500); //ping again for result every 1/2 second
				}
			},
			failure: function(response, object){
				var userMessage = CCS.Translator.getText("Error code")+': '+ response.status +"<br />"+
						"url: "+ object.url +"<br />"+
						"text: "+ response.statusText +"<br />"+
						"scope: "+ response.request.options.scope.id +"<br />"+
						"timeout: ";
				userMessage += response.timedout === true? CCS.Translator.getText("Yes") : CCS.Translator.getText("No");
				userMessage += "<br /><br />"+CCS.Translator.getText("Are you sure you want to continue?");

				Ext.MessageBox.show({
					icon: Ext.MessageBox.WARNING,
					title: CCS.Translator.getText("Some errors occurred"),
					msg: userMessage,
					buttons: Ext.MessageBox.OKCANCEL,
					animateTarget: me.getEmptyContainer(),

					fn: function(response) {
						if(response == 'ok') {
							setTimeout(function() {
								me.ping(guiid);
							}, 2000); //ping again
						}
						else {
							document.location.reload();
						}
					}
				});
			},
			scope: this
		});
	},

	create: function(btn) {
		btn.blur();
		this.getRestriction().setLoading(true);
		var params = MyApp.app.getController('Content').params;

		var data = {
			system : '',
			client : '',
			project: '',
			object_class : '',
			object: '',
			field : '',
			comment : this.getRestrictionForm().getForm().findField('comment').getValue(),
			status : 'A',
			audit_user : params.user,
			audit_system : params.system,
			audit_client : params.client,
			audit_timestamp : null
		};


		var type = this.getRestrictionForm().getForm().findField('type').getValue();
		switch(type) {
			case 1: //orglvl
				data.field = this.getRestrictionForm().getForm().findField('field').getValue();
			break;
			case 2: //object class
				data.object_class = this.getRestrictionForm().getForm().findField('field').getValue();
			break;
			case 3: //object
				data.object = this.getRestrictionForm().getForm().findField('field').getValue();
			break;
			case 4: //field
				data.field = this.getRestrictionForm().getForm().findField('field').getValue();
			break;
			case 5: //tcode
				data.object = 'S_TCODE';
				data.field = 'TCD';
				data.low = this.getRestrictionForm().getForm().findField('low').getValue();
				data.high= this.getRestrictionForm().getForm().findField('high').getValue();
				data.value = data.high.length > 0? data.low +"-"+ data.high : data.low;
			break;
		}

		var scope = this.getRestrictionForm().getForm().findField('scope').getValue();
		switch(scope) {
			case 1:
			break;
			case 2:
				data.system = params.system;
				data.client = params.client;
			break;
			case 3:
				data.project = params.projectName;
			break;
		}

		var store = MyApp.app.getStore('restrictions');
		var myNewRecord = new MyApp.model.restriction(data);
		store.add(myNewRecord);

		var me = this;
		setTimeout(function() {
			me.getRestriction().close();
			me.getRestriction().setLoading(false);
			store.load();
		}, 500);

	}

});
