// JavaScript Document
//Author MySirt 28/05/2017 
var app = angular.module('UserMApp', []);

app.controller('UserMCtrl', function($scope, $http, $window, $location) {
	// INIT FUNCTION 
	$scope.init=function(seq){
		$scope.messageError=true;
		$scope.status = 'done';
		
		$scope.urlUserMService='servlet/Maat.servlet.UserMServices';
		$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
		
		$scope.userM={
				Cliente:'',
				NomeCliente:'',
				UserM:'',
				Password:'',
				Role:'',
				PageToGo:'',
				Directory:'',
				LastLogin:'',
				InProva:'Si',
				PrimaryKey_MySirt:'',
				sequentialUniqueNbr:''
		};

$scope.showClienteList=false;
$scope.Cliente={ 
utente:$scope.userM.UserM
,Tipo_cliente:''
,Tipologia:''
,Cognome:''
,Denominazione:''
,CodiceFiscale:''
,Nome:''
,Email_address:''
,Registration_date:''
,Indirizzo:''
,Citta:''
,CAP:''
,Provincia:''
,Contatto:''
,Note:''
,PrimaryKey_MySirt:''
,PrintableTemplate:''
,EntityName:''
 };
		if (seq!='null'&seq!='0'&seq!=null&seq!=''){
			$scope.action='updateUserM';
			$scope.titleForm='Aggiornamento  UserM';
			$scope.titleButton='Aggiorna';
			$scope.getUserM(seq);
		} else{
			$scope.action='insertUserM';
			$scope.titleForm='Inserimento UserM';
			$scope.titleButton='Inserire';
			//in fase di init riempi tutte le combo che non hanno condizioni
		}
	}
 $scope.resetClienteList = function (){
      $scope.cleanCliente();
      $scope.showClienteList=false; 
 }
  $scope.cleanCliente = function () {
	  $scope.Cliente.PrimaryKey_MySirt=''; 
	  $scope.userM.Cliente='';
 	  $scope.Cliente.Nome='';
 	  $scope.Cliente.CodiceFiscale='';
	  $scope.userM.NomeCliente='';
   }
	$scope.updateClienteConnections= function() {
		$scope.userM.Cliente=$scope.Cliente.PrimaryKey_MySirt;
         for(var i = 0 ; i< $scope.ClienteList.length; i++){
            var obj =  $scope.ClienteList[i];
            if (obj.PrimaryKey_MySirt==$scope.userM.Cliente) {
               $scope.userM.NomeCliente=$scope.ClienteList[i].Nome;
               return;
            }
         }
		//per le combo che hanno connessioni nel change popoli la combo relativa
	}
	$scope.getClienteList = function (primaryKey, utente) {

		document.body.style.cursor = "wait";
		$http({
	            url : 'servlet/Maat.servlet.ClienteServices',
	            method : "GET",
	            params: {
	            	actionToDo: 'fill',
	            	ffs1: 'PrimaryKey_MySirt',
	                fieldToSelectText:'PrimaryKey_MySirt',
	                fieldName: 'PrimaryKey_MySirt',
	                utente:utente,
	                utente:utente
,PrimaryKey_MySirt:primaryKey
,Nome:$scope.Cliente.Nome
,CodiceFiscale:$scope.Cliente.CodiceFiscale
	            }
	        }).then(function (response) {
	        	$scope.ClienteList = response.data.ClienteList;
				$scope.showClienteList=true; 
	        	if ($scope.userM.Cliente!=null && $scope.userM.Cliente!='' )  {
	        		$scope.selectCliente($scope.userM.Cliente);
	        	}
           		document.body.style.cursor = "default";
	        }, function(response) {
	            //fail case
	        	$scope.requestResult=response;
           		document.body.style.cursor = "default";
	        });	
	};
	
	$scope.selectCliente = function(){
		//attenzione alle maiuscole e alle minuscole dei nome per il nome delle colonne nel db
		//e come le definisci nel def....
		
		for(var i = 0 ; i< $scope.ClienteList.length; i++){
	        var obj =  $scope.ClienteList[i];
	        if (obj.PrimaryKey_MySirt==$scope.userM.Cliente) {
	        	$scope.Cliente=$scope.ClienteList[i];
	        	$scope.updateClienteConnections();
	        	return;
	        }
	    }
	}
	$scope.getUserM = function (seq) {

		document.body.style.cursor = "wait";
		$http({
	            url : $scope.urlUserMService,
	            method : "GET",
	            params: {
	            	actionToDo: 'getUserM',
	            	SU: seq
	            }
	        }).then(function (response) {
	        	$scope.userM = response.data.UserM[0];
$scope.ClienteList = response.data.Cliente;
$scope.Cliente=$scope.ClienteList[0];
$scope.showClienteList=true;
			    $scope.LastLogin=$scope.userM.LastLogin;
           document.body.style.cursor = "default";
	        }, function(response) {
	            //fail case
	        	$scope.requestResult=response;
           	document.body.style.cursor = "default";
	        });	
	};	

	$scope.checkUnique = function (name,value) {
	if (value==null || value=='') {
	 	return;
	}
		document.body.style.cursor = "wait";
        $http({
        url: $scope.urlUserMService,
        method: 'POST',
        params: {
			actionToDo: 'checkUnique',
			fieldToVerify: name,
			valueToVerify: value
        },
        data: $scope.userM
    	}).success(function (data) {
    	if (data.indexOf('<Message>OK')==-1){
		   if (data.indexOf('<Error>')!=-1) {
			   $window.alert(data.substring(data.indexOf('<Error>')+7,data.indexOf('</Error>')));
		   } else{
    			$window.alert(data.substring(data.indexOf('<Message>')+9,data.indexOf('</Message>')));
		if (name=='UserM'){
	    		$scope.userM.UserM="";
		}
		if (name=='PrimaryKey_MySirt'){
	    		$scope.userM.PrimaryKey_MySirt="";
		}
           }
    	} 
           	document.body.style.cursor = "default";
    }, function(response) {
               document.body.style.cursor = "default";
        //fail case
    	$window.alert(data);
    });	
   };
     
	$scope.submitUserM = function(){
      if ($scope.allRequiredFieldsAreValued()){
		$scope.status = 'running';
		document.body.style.cursor = "wait";
        $http({
            url: $scope.urlUserMService,
            method: 'POST',
            params: {
            	actionToDo: $scope.action
           },
            data: $scope.userM
        }).then(function (response) {
        	if (response.data.indexOf('<Error>')!=-1){
        		$window.alert(response.data.substring(response.data.indexOf('<Error>')+7,response.data.indexOf('</Error>')));
        	} else {
        		$window.alert('Operazione avvenuta con successo');

		$window.location.href= 'UserMSearch.jsp';
        	}
           	document.body.style.cursor = "default";
				$scope.status = 'done';
	        }, function(response) {
	            //fail case
     			$scope.requestResult=response;
           	document.body.style.cursor = "default";
				$scope.status = 'done';
	        });		
	   };		
	};
      $scope.allRequiredFieldsAreValued = function (){
	var vLastLogin = angular.element('#LastLogin').val();
	$scope.userM.LastLogin=vLastLogin;
      	$scope.execCalc();	
      	return (true);	
      };
      $scope.back = function(){
    	  $window.history.go(-1);
      };
   
$scope.execCalc = function(){
try{
$scope.userM.PrimaryKey_MySirt= ( $scope.userM.UserM).toString();
if ($scope.userM.UserM!= ''){
 	$scope.checkUnique('PrimaryKey_MySirt',$scope.userM.PrimaryKey_MySirt);
}
		} catch(err) {
    		$window.alert('execCalc errore: '+err.message);
		}
    };
});
