//
// r3remoteGrid
// Felix Kosmalla
//
//
// erbt von r3BaseGrid
// 
// über loadStructure wird der Name der Datenbank Tabelle gesetzt
//
// über CRUD wird das Model geladen
//


// Events
//
// onStructureLoaded 	Wenn die Struktur geladen wurde


var r3remoteGrid = Ext.extend(r3baseGrid, {

	
	// loadStructure
	// 
	// config Objekt
	// 
	loadStructure:function(config){
		Ext.apply(this,config);
		this.backend = config.backendUrl;
		// this.tableName = config.tableName;
		
		
		Ext.Ajax.request({
			url: this.backend + this.tableName + '/Model',
			success: this.checkForComboStores,
			scope:this,
			method:'POST'
		});
		
		
			

		
		return this;
	},
	
	
	// checkForComboStores
	// 
	// überprüft ob Comboboxen enthalten sind und lädt die jeweiligen stores
	// 
	checkForComboStores:function(response){
		var tableOptions = Ext.util.JSON.decode(response.responseText);

		//init comboStores
		this.multiStores = new Object();
		this.multiStoresRaw = new Object();
		
		var comboCount = 0;
		
		Ext.each(tableOptions.fields, function(item){
			if(item.r3type == 'combo' || item.r3type == 'select_many' || item.r3type == 'select_one_radio'){
				comboCount++;				
			}
		});
		
		var requestCount = 0;
		
		// für Selectboxen und Multiselects
		Ext.each(tableOptions.fields, function(item){

			if(item.r3type == 'combo' || item.r3type == 'select_many' || item.r3type == 'select_one_radio'){


				Ext.Ajax.request({
					url: this.backend + item.fTable + "/" + item.fTableLabel + '/ComboStore',
					method:'POST',
					scope:this,
					success: function(response){
						requestCount++;
						// SimpleStore für Combobox erstellen
						var crudData = Ext.util.JSON.decode(response.responseText);
						
						this.multiStoresRaw[item.fTable+'_'+item.fTableLabel] = crudData.raw;
						
						var simpleStore = new Ext.data.SimpleStore(crudData);				
						
						this.multiStores[item.fTable+'_'+item.fTableLabel] = simpleStore;
						
						if(requestCount == comboCount){
							this.startGrid(tableOptions);
						}
						
					}
				});


			}
		},this);
		
		if(comboCount==0){
			this.startGrid(tableOptions);				
		}

	},
	
	
	
	// startGrid
	// 
	// verarbeitet Ajax Request und initiert die Klasse
	// 
	startGrid:function(tableOptions){
		// var tableOptions = Ext.util.JSON.decode(response.responseText);

		// console.log('tableOptions',tableOptions);

		// Sonderfälle behandeln
		//AddPanel
		// Ext.each(tableOptions.addPanelOptions)







		this.init(tableOptions);
		this.onStructureLoaded();

	},
	
	
	// onStructureLoaded
	// 
	// EVENT
	// 
	onStructureLoaded:function(){
		
	}
	
	
	
	
	
	
});
