 // vim: sw=4:ts=4:nu:nospell:fdc=4
 /*global Ext, EQP */
 /**
 * Classe base que implementa as fun��es b�sicas dos m�dulos
 *
 * @author Ot�vio Augusto
 * @copyright (c) 2009, by Ot�vio Augusto
 * @company Net On - Solu��es Tecnol�gicas
 * @date 7 de Setembro 2009
 *
 */

//Define o namespace
Ext.ns('App.Module');

//Cria a classe base a ser estendida
App.Module = Ext.extend(Ext.Panel,{		
	/**
	 * Inicializa o componente
	 */
	initComponent : function(){		
		//Quantos data stores devem ser carregados antes de 
		this.waitStore = 0;
		
		//Registra eventos customizados para os componentes
		this.addEvents('beforeinsert','beforeupdate','beforeedit','beforecreate');

		//Cria a barra de a��es principal
		this.actionBar = {
				xtype: 'toolbar',
				items:[
				/*{
					text: 'Salvar',
					iconCls: 'save-icon',
					scope: this,
					handler: this.insertRecord
				},'-',*/
				{
					text: 'Novo',
					iconCls: 'ui-add-icon',
					tooltip: 'Adicionar novo registro',
					handler: this.createRecord,
					scope: this
				
				},
				{
					text: 'Editar',
					iconCls: 'ui-edit-icon',
					tooltip: 'Editar registro selecionado',
					handler: this.editRecord,
					scope: this
					
				},
				{
					text: 'Deletar',
					iconCls: 'ui-delete-icon',
					scope: this,
					handler: this.deleteRecord,
					tooltip: 'Deletar registro selecionado'
				}				
			]
		};		
		
		var config = {
			layout: 'fit',
			border: false,
			items:[
				this.createGrid()
			]
		};
					
		//Registra evento de carregamento autom�tico do datastore
		this.on('show',function(){
			var id = this.id + '-grid';
			var grid = Ext.getCmp(id);
			
			try{
				this.store.load({params:{start: 0, limit: 200}});
			}catch(e){}
			
			grid.syncSize();
			this.doLayout();
		},this);
				
		
		//Sobrescreve a configura��o default
		Ext.apply(this,config);

		//Chama o initComponent da super classe
		App.Module.superclass.initComponent.apply(this, arguments);		
	},
	
	/**
	 * Sobrescreve o m�todo de renderiza��o do componente
	 */
	onRender : function(ct, position){
		//Chama o m�todo de renderiza��o da superclasse		
		App.Module.superclass.onRender.call(this, ct, position);

		//Registra evento para o dblclick do grid
		var grid = Ext.getCmp(this.id + '-grid');
		grid.on('dblclick',this.editRecord, this);
	},
	
	/**
	 * Abre a janela de inser��o
	 */
	createRecord : function(){
		//Se a janela n�o existir,
		if (!this.window)
			//Cria a mesma
			this.createForm();
			
		try{
			Ext.getCmp(this.id+'-save-btn').handler = this.insertRecord;
                        //Reseta o formul�rio
                        this.form.form.reset();
		}catch(e){}
		
		//Aciona o evento
		this.fireEvent('beforecreate',this);		
		
		//Abre a janela de inser��o
		this.window.show();
	},
	
	/**
	 * Abre a janela do formul�rio para a inser��o
	 */
	editRecord : function(){
		//Recupera o registro selecionado
		var record = this.getSelectedRecord();
				
		//Se o registro n�o existir, 
		if (!record){
                    Ext.ux.MessageBox.flash({
                        msg: 'Nenhum registro foi selecionado!',
                        type: 'warning',
                        pause: 3
                    });
                }else{
			if (!this.window)
				//Cria a mesma
				this.createForm();								
    		
                                //Exibe a janela de edi��o
                                this.window.show();
    		
                                //Aciona o evento
                                this.fireEvent('beforeedit',this,record);
    		
			try{
				Ext.getCmp(this.id+'-save-btn').handler = this.updateRecord;
			}catch(e){}
				
			//Seta o formul�rio com os valores do registro selecionado
                        this.form.form.setValues(record.data);
                }
    	
    	
	},
	
	/**
	 * Insere o registro no banco de dados
	 * 
	 */
	insertRecord : function(button){
		if (this.validadeForm()){
                    this.params = this.form.form.getValues();

                    //Aciona o evento de pr�-inser��o
                    this.fireEvent('beforeinsert',this);

                    //this.form.disable();

                   this.loaderTarget = button;
                   Ext.ux.Loader.start({sender: button, waitingText: 'Salvando...'});

                    Ext.Ajax.request({
                       url: App.sysURL + this.moduleAction + 'save/',
                       success: this.successInsert,
                       failure: this.failureInsert,
                       params: this.params,
                       scope: this			
                    });                    
                }else
                    this.throwValidationError()
	},
	
	/**
	 * Confirma a inser��o do registro
	 * 
	 */
	successInsert : function(){

            Ext.ux.MessageBox.flash({
                msg: 'O registro foi inserido com &ecirc;xito!',
                type: 'success'
            });

           
           Ext.ux.Loader.stop(this.loaderTarget);

            //this.form.enable();

            this.window.hide();
            Ext.getCmp(this.id + '-grid').store.load();

	},
	
	
	/**
	 * Atualiza o registro no banco de dados
	 */
	updateRecord : function(button){
            if (this.validadeForm()){
                //Recupera os valores dos campos
		this.params = this.form.form.getValues();
		
		//Aciona o evento de pr�-inser��o
		this.fireEvent('beforeupdate',this);		

               this.loaderTarget = button;
               Ext.ux.Loader.start({sender: button, waitingText: 'Atualizando...'});

		//this.form.disable();

		Ext.Ajax.request({
		   url: App.sysURL + this.moduleAction + 'save/',
		   success: this.successUpdate,
		   failure: this.failureUpdate,
		   params: this.params,
		   scope: this
		});
            }else
                this.throwValidationError();
	},
	
	/**
	 * Exibe mensagem de confirma��o de atualiza��o e recarrega o grid
	 */
	successUpdate : function(){
            Ext.ux.MessageBox.flash({
                msg: 'O registro foi atualizado com &ecirc;xito!',
                type: 'success'
            });
            //this.form.enable();
           Ext.ux.Loader.stop(this.loaderTarget);

            this.window.hide();
            Ext.getCmp(this.id + '-grid').store.load();

	},
	
	/**
	 * Exclui o registro selecionado
	 */
	deleteRecord : function(button){
		var record = this.getSelectedRecord();
		
		if (record){
			//Solicita a confirma��o da exclus�o do registro
			Ext.MessageBox.confirm('Confirma&ccedil;&atilde;o', 'Deseja realmente excluir este registro?',
				function(btn){	
					if (btn == 'yes'){
                                               this.loaderTarget = button;
                                               Ext.ux.Loader.start({sender: button, waitingText: 'Deletando...'});
                                                
						Ext.Ajax.request({
						   url: App.sysURL + this.moduleAction + 'delete/',
						   success: this.successDelete,
						   failure: this.failureDelete,
						   params: {id: record.get('id')},
						   scope: this
						});
					}
				},this
			);
		}else{
                    Ext.ux.MessageBox.flash({
                        msg: 'Nenhum registro foi selecionado!',
                        type: 'warning',
                        pause: 3
                    });
		}				
	},
	
	/**
	 * Confirma a exclus�o do registro
	 */
	successDelete : function(){
            Ext.ux.Loader.stop(this.loaderTarget);
            
            Ext.ux.MessageBox.flash({
                msg: 'O registro foi exclu&iacute;do com &ecirc;xito!',
                type: 'success'
            });

            Ext.getCmp(this.id + '-grid').store.load();
            delete(this.loaderTarget);

		
	},
	
	/**
	 * Cancela uma a��o de edi��o ou inser��o
	 */
	cancel : function (){
		//Solicita a confirma��o do cancelamento
		Ext.MessageBox.confirm('Confirma&ccedil;&atilde;o', 'Deseja realmente cancelar esta a&ccedil;&atilde;o?',
			function(btn){
				if (btn == 'yes'){
					//Reseta o formul�rio de edi��o
					this.form.form.reset();
					
					//Fecha o formul�rio
					this.window.hide();							
				}
			},this
		);
	},
	
	/**
	 * Recupera o registro selecionado em um data grid
	 */
	getSelectedRecord : function(){
            var grid = Ext.getCmp(this.id + '-grid');

            //Recupera o SelectionModel do grid
            var sm = grid.getSelectionModel();

            //Verifica se o grid possui a propriedade selection
            if (sm.selection){
                    return sm.selection.record;
            }else{
	    	//Verifica se o grid possui o m�todo getSelected()
	    	try{
	    		return sm.getSelected();
	    	}catch(e){
	    		return false
	    	}
            }
    			
	},

        /**
         * Valida o formulário
         */
        validadeForm : function(){
            if (this.form.form.isValid())
                return true;
            else
                return false;
        },

        /**
         * Lança 
         */
        throwValidationError : function(){
            Ext.ux.MessageBox.flash({
                msg: 'Os campos em destaque s&atilde;o obrigat&oacute;rios!',
                type: 'error',
                pause: 3
            });
        }
	
});


