myApp.controller("assignAccountsController",function($scope, myFactory, $mdDialog, $http, appConfig, $timeout, $element, $window){
	$scope.records = [];
	$scope.parentData = {
			"accountId": "",
			"accountName": "",
			"industryType":"",
			"status":"",
			"deliveryManagers":[],
			"action":""
	};
	var getCellTemplate = '<p class="col-lg-12"><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true" style="font-size:1.5em;margin-top:3px;cursor:pointer;" data-placement="center" title="View" onmouseenter="$(this).tooltip(\'show\')" ng-click="grid.appScope.getRowData(row,\'Update\')"></i>'+
	'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-minus-circle fa-2x" aria-hidden="true" style="font-size:1.5em;margin-top:3px;cursor:pointer;" data-placement="left" title="Delete" onmouseenter="$(this).tooltip(\'show\')" ng-click="grid.appScope.getRowData(row,\'Delete\')"></i></p>';
	$scope.gridOptions = {
			paginationPageSizes : [ 10, 20, 30, 40, 50, 100],
			paginationPageSize : 50,
		    pageNumber: 1,
			pageSize:10,
			enableFiltering: true,
			columnDefs : [ 
				{field : 'accountId',displayName: 'Account ID', enableColumnMenu: true, enableSorting: true,enableFiltering: true, width:120,cellClass: 'grid-align'},
				{field : 'accountName',displayName: 'Account Name', enableColumnMenu: false, enableSorting: false,enableFiltering: true,cellClass: 'grid-align'},
				{field : 'industryType',displayName: 'Industry Type', enableColumnMenu: false, enableSorting: true,enableFiltering: true,cellClass: 'grid-align'}, 
				{field : 'status',displayName: 'Status', enableColumnMenu: false, enableSorting: true,enableFiltering: true,cellClass: 'grid-align'}, 
				{field : 'deliveryManagers',displayName: 'Account Managers',  cellTemplate: '<div ng-repeat= "item in row.entity[col.field]">{{item.employeeName}}<span ng-hide="$last">,</span></div>' ,enableColumnMenu: false, enableSorting: true,enableFiltering: false,cellClass: 'grid-align'}, 
				{name : 'Actions', displayName: 'Actions',cellTemplate: getCellTemplate, enableColumnMenu: false, enableSorting: false, enableFiltering:false,width:130} 
			]
		};
	$scope.gridOptions.data = $scope.records;
	$scope.getRowData = function(row, action){
		$scope.parentData.accountId = row.entity.accountId;
		$scope.parentData.accountName = row.entity.accountName;
		$scope.parentData.industryType = row.entity.industryType;
		$scope.parentData.deliveryManagers = row.entity.deliveryManagers;
		$scope.parentData.status = row.entity.status;
		if(action == "Update")
			$scope.updateAccount(action, $scope.parentData);
		else if(action == "Delete")
			$scope.deleteAccount(row,action);
	}
	$scope.refreshPage = function(){
		$scope.getAccountDetails();
	}
	$scope.getAccountDetails = function(){
		$http({
	        method : "GET",
	        url : appConfig.appUri + "account/accounts"
	    }).then(function mySuccess(response) {
	    	console.log(response.data);
	    	  $scope.gridOptions.data=response.data;  
	    }, function myError(response) {
	    	showAlert("Something went wrong while fetching data!!!");
	    	$scope.gridOptions.data = [];
	    });
	};
	$scope.addAccount = function(action, userData){
		$('#home').addClass('md-scroll-mask');
		userData.action = action;
		$mdDialog.show ({
            clickOutsideToClose: true,
            scope: $scope,        
            preserveScope: true,           
            templateUrl: 'templates/newAccount.html',
            controller: addController,
            locals:{dataToPass: userData,gridOptionsData: $scope.gridOptions.data},
         }).then(function(result) {
		    	if(result == "Add") showAlert('Account assigned successfully');
		    	else if(result == "Update") showAlert('Account updated successfully');
		    	else if(result == "Cancelled") console.log(result);
		    	else showAlert('Account assigning/updation failed!!!');
		    });
	}
//	$scope.updateAccount = function(action, userData){
//		$('#home').addClass('md-scroll-mask');
//		userData.action = action;
//		$mdDialog.show ({
//            clickOutsideToClose: true,
//            scope: $scope,        
//            preserveScope: true,           
//            templateUrl: 'templates/newAccount.html',
//            controller: addController,
//            locals:{dataToPass: userData,gridOptionsData: $scope.gridOptions.data, employees: $scope.employees},
//         }).then(function(result) {
//		    	if(result == "Add") showAlert('Account assigned successfully');
//		    	else if(result == "Update") showAlert('Account updated successfully');
//		    	else if(result == "Cancelled") console.log(result);
//		    	else showAlert('Account assigning/updation failed!!!');
//		    });
//	}
	function showAlert(message) {
		$mdDialog.show($mdDialog.alert().parent(
				angular.element(document.querySelector('#popupContainer')))
				.clickOutsideToClose(true).textContent(message).ariaLabel(
						'Alert Dialog').ok('Ok'));
	}
	$scope.deleteAccount = function(row,action){
		$('#home').addClass('md-scroll-mask');
	    var confirm = $mdDialog.confirm()
	    	  .clickOutsideToClose(true)
	          .textContent('Are you sure you want to delete this account?')
	          .ok('Ok')
	          .cancel('Cancel');
	    $mdDialog.show(confirm).then(function() {
	    	deleteAccountRole(row.entity.accountId);
	    	$timeout(function(){updateGridAfterDelete()},500);
	    }, function() {
	    	console.log("Cancelled dialog");
	    });
	};
	function deleteAccountRole(accountId){
		var req = {
				method : 'DELETE',
				url : appConfig.appUri+ "account/accounts?accountId="+accountId
			}
			$http(req).then(function mySuccess(response) {
				$scope.result = "Success";
			}, function myError(response){
				$scope.result = "Error";
			});
	}
	function updateGridAfterDelete(){
		if($scope.result == "Success"){
			$scope.refreshPage();
			showAlert('Account deleted successfully');
		}else if($scope.result == "Error"){
			showAlert('Something went wrong while deleting the account.')
		}
	}
	
	function addController($scope, $mdDialog, dataToPass, gridOptionsData, $mdSelect) {
		$scope.accountName;
		$scope.industryType;
		$scope.clientAddress;
		$scope.searchTerm;
		$scope.templateTitle=dataToPass.action;
		$scope.accountValidationMessage='';
		$scope.addButtonvisible=false;
		$scope.managerDetails = [];
		$scope.managersSelectedList = [];
        $scope.employeeInTeam = []; 
		$scope.industryTypesList = ['Retail','Finance', 'HealthCare','Government','Insurance'];
		$window.addEventListener('click',function(e){
			if(e.target.type !== 'search'){
				 $mdSelect.hide();
			}
		})
		$scope.getDeliveryManagers = function(){
			$http({
		        method : "GET",
		        url : appConfig.appUri + "/projectTeam/getEmployeesToTeam"
		    }).then(function mySuccess(response) {
		    	$scope.managerDetails=response.data;
		    }, function myError(response) {
		    	showAlert("Something went wrong while fetching data!!!");
		    	$scope.gridOptions.data = [];
		    });
		};
		$scope.duplicateAccNameValidation = function(){
			$http({
		        method : "GET",
		        url : appConfig.appUri + "/account/accounts/"+$scope.accountName
		    }).then(function mySuccess(response) {
		    	if(response.data =='Account already exist'){
		    		$scope.alertMsg=response.data;
		    		$scope.addButtonvisible=true;
		    		$('#addButton').addClass('addButtonDisable');
		    	}else{
		    		//$scope.alertMsg=response.data;
		    		$scope.addButtonvisible=false;
		    		$('#addButton').removeClass('addButtonDisable');
		    	}
		    	
		    }, function myError(response) {
		    	showAlert("Something went wrong while fetching data!!!");
		    });
		}
		$scope.cancel = function(){
			   $mdDialog.hide("Cancelled");
		}
	    $scope.updateSearch = function (e) {
	            e.stopPropagation();
	    }
	    $scope.searchFilter = function (obj) {
	            var re = new RegExp($scope.searchTerm, 'i');
	            return !$scope.searchTerm || re.test(obj.employeeName);
	    };
        $scope.removeSelectedLead = function(item){
            var index = $scope.managersSelectedList.indexOf(item);
            $scope.employeeInTeam.splice(index,1);
            $scope.managersSelectedList.splice(index,1);
        }
        $scope.getSelectedLead = function(){
            $scope.managersSelectedList.forEach(function(manager){
                if(!$scope.employeeInTeam.includes(manager.employeeId))
                $scope.employeeInTeam.push(manager.employeeId)      
            })
            console.log($scope.employeeInTeam);
        }
		$scope.getIndustryTypeSelected = function(){
			if ($scope.industryType !== undefined) {
				$scope.industryType = $scope.industryType;
				return $scope.industryType;
			} else {
				return "Please select a Industry Type";
			}
		};
	    $scope.clearSearchTerm = function() {
	        $scope.searchTerm = '';
	    };
	    $element.find('input').on('keydown', function(ev) {
	          ev.stopPropagation();
	    });
	  
      $scope.validateFields = function(){
    	  var managersSelectedList = $scope.managersSelectedList;
    	  var accountName = $scope.accountName;
    	  var industryType = $scope.industryType;
    	  var clientAddress = $scope.clientAddress;
    	  $scope.accountManagers = function(){
				var employeeIdsArray = [];
				for(i=0;i< $scope.managersSelectedList.length;i++){
					 employeeIdsArray[i] =$scope.managersSelectedList[i].employeeId;
				}
				return employeeIdsArray;
		  }
			if(managersSelectedList == undefined){
				$scope.alertMsg = "Please select a accountManager";
			document.getElementById('selectManager').focus();
			}else if(accountName == undefined){
				$scope.alertMsg = "Please enter the account Name";
				document.getElementById('accountName').focus();
			}else if(industryType == undefined){
				$scope.alertMsg = "Please enter the industry type";
				document.getElementById('industryType').focus();
			}else if(clientAddress == undefined){
				$scope.alertMsg = "Please enter the client address";
				document.getElementById('clientAddress').focus();
			}
			else{
				$scope.alertMsg = "";
				var record = {"accountName":$scope.accountName,"industryType":$scope.industryType,"clientAddress":$scope.clientAddress,"deliveryManagers":$scope.accountManagers()};
				console.log(record);
				addingAccount(record,$scope.templateTitle);
				$timeout(function(){updateGrid($scope.templateTitle, record)},500);
			}
		};
		addingAccount = function(record,action){
			var urlRequest  = "";
			if(action == "Add"){
				urlRequest = appConfig.appUri+ "/account/accounts";
			//}else if(action == "Update"){
				//urlRequest = appConfig.appUri+ "project/updateProject";
			}
			var req = {
				method : 'POST',
				url : urlRequest,
				headers : {
					"Content-type" : "application/json"
				},
				data : record
			}
			$http(req).then(function mySuccess(response) {
				$scope.result = "Success";
				}, function myError(response){
				$scope.result = "Error";
			});
		}
		function updateGrid(action, record){
			if($scope.alertMsg == ""){
				if($scope.result == "Success"){
					if(action == "Add" || action == "Delete"){
						$scope.refreshPage();
					}
						//else if(action == "Update"){
//						var existingRecord = getRowEntity($scope.projectId);
//						var index = gridOptionsData.indexOf(existingRecord);
//						gridOptionsData[index] = record;
//					}
					$mdDialog.hide(action);
				}else{
					$mdDialog.hide("Error");
				}
				
			}
		}	
	}
});