myApp.controller("assignRoleController",function($scope, myFactory, $mdDialog, $http, appConfig, $timeout){
	$scope.records = [];
	$scope.empSearchId = "";
	$scope.status = "Active";
	$scope.parentData = {
			"employeeId": "",
			"employeeName": "",
			"emailId":"",
			"designation":"",
			"action":"",
			"passportExpiryDate":""
	};
	
	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;" 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;" 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 : 'employeeId',displayName: 'Employee ID', enableColumnMenu: true, enableSorting: true,enableFiltering: true, width:120,cellClass: 'grid-align'},
			{field : 'employeeName',displayName: 'Name', enableColumnMenu: true, enableSorting: true,enableFiltering: true,cellClass: 'grid-align'},
			{field : 'mobileNumber',displayName: 'Mobile', enableColumnMenu: false, enableSorting: false,enableFiltering: false,cellClass: 'grid-align'},
			{field : 'emailId',displayName: 'Email', enableColumnMenu: false, enableSorting: false,enableFiltering: true,cellClass: 'grid-align'},
			{field : 'baseTechnology',displayName: 'Skill', enableColumnMenu: false, enableSorting: false,enableFiltering: true,cellClass: 'grid-align'},
			{field : 'designation',displayName: 'Designation', enableColumnMenu: false, enableSorting: true,enableFiltering: true,cellClass: 'grid-align'}, 
			{name : 'Actions', displayName: 'Actions',cellTemplate: getCellTemplate, enableColumnMenu: false, enableSorting: false,enableFiltering: false, width:100,cellClass: 'grid-align'} 
		]
	};
	$scope.gridOptions.data = $scope.records;
	$scope.gridOptionsOrgView = {
			paginationPageSizes : [ 10, 20, 30, 40, 50, 100],
			paginationPageSize : 10,
		    pageNumber: 1,
			pageSize:10,
			enableFiltering: true,
			columnDefs : [ 
				{field : 'employeeId',displayName: 'Employee ID', enableColumnMenu: true, enableSorting: true,enableFiltering: true, width:120},
				{field : 'employeeName',displayName: 'Name', enableColumnMenu: true, enableSorting: true,enableFiltering: true},
				{field : 'emailId',displayName: 'Email', enableColumnMenu: false, enableSorting: false,enableFiltering: true},
				{field : 'baseTechnology',displayName: 'Skill', enableColumnMenu: false, enableSorting: false,enableFiltering: true},
				{field : 'designation',displayName: 'Designation', enableColumnMenu: false, enableSorting: true,enableFiltering: true}, 
				{field : 'functionalGroup',displayName: 'Functional Org', enableColumnMenu: false, enableSorting: true,enableFiltering: true, width:120} 
				
			]
		};
	
	$scope.getRowData = function(row, action){
		$scope.parentData.employeeId = row.entity.employeeId;
		$scope.parentData.employeeName = row.entity.employeeName;
		$scope.parentData.gender = row.entity.gender;
		$scope.parentData.emailId = row.entity.emailId;
		$scope.parentData.role = row.entity.role;
		$scope.parentData.empLocation = row.entity.empLocation;
		$scope.parentData.designation = row.entity.designation;
		$scope.parentData.functionalGroup = row.entity.functionalGroup;
		$scope.parentData.empStatus = row.entity.empStatus;	
		$scope.parentData.employmentType = row.entity.employmentType;
		$scope.parentData.domain = row.entity.domain;
		$scope.parentData.dateOfJoining = row.entity.dateOfJoining;
		$scope.parentData.dateOfBirth = row.entity.dateOfBirth;
		$scope.parentData.hasPassort = row.entity.hasPassort;
		$scope.parentData.hasB1 = row.entity.hasB1;
		$scope.parentData.passportExpiryDate = row.entity.passportExpiryDate;
		$scope.parentData.b1ExpiryDate = row.entity.b1ExpiryDate;
		
		
		
		if(action == "Update")
			$scope.assignRole(action, $scope.parentData);
		else if(action == "Delete")
			$scope.deleteRole(row);
	}
	
	$scope.refreshPage = function(){
		$scope.empSearchId = "";
		$scope.getUserRoles();
	}
	
	$scope.refreshPageOrg = function(){
		$scope.getOrgEmps();
	}
	
	var gridOptionsReport = {
			paginationPageSizes : [ 10, 20, 30, 40, 50, 100],
			paginationPageSize : 10,
		    pageNumber: 1,
			pageSize:10,
			enableFiltering: true,
			columnDefs : [ 
				{field : 'employeeId',displayName: 'Employee ID', enableColumnMenu: true, enableSorting: true,enableFiltering: true, width:120},
				{field : 'employeeName',displayName: 'Name', enableColumnMenu: false, enableSorting: false,enableFiltering: true},
				{field : 'mobileNumber',displayName: 'Mobile', enableColumnMenu: false, enableSorting: false,enableFiltering: false},
				{field : 'emailId',displayName: 'Email', enableColumnMenu: false, enableSorting: false,enableFiltering: true},
				{field : 'baseTechnology',displayName: 'Skill', enableColumnMenu: false, enableSorting: false,enableFiltering: true},
				{field : 'designation',displayName: 'Designation', enableColumnMenu: false, enableSorting: true,enableFiltering: true}, 
				{name : 'Actions', displayName: 'Actions',cellTemplate: getCellTemplate, enableColumnMenu: false, enableSorting: false,enableFiltering: false, width:100} 
			]
		};
	$scope.getUserRoles = function(){
		$http({
	        method : "GET",
	        url : appConfig.appUri + "user/getEmployeeByStatus?status="+$scope.status
	    }).then(function mySuccess(response) {
	        $scope.gridOptions.data = response.data;
	    }, function myError(response) {
	    	showAlert("Something went wrong while fetching data!!!");
	    	$scope.gridOptions.data = [];
	    });
	};
	
	$scope.getOrgEmps = function(){
		$http({
	        method : "GET",
	        url : appConfig.appUri + "user/getUserRoles"
	    }).then(function mySuccess(response) {
	        $scope.gridOptionsOrgView.data = response.data;
	    }, function myError(response) {
	    	showAlert("Something went wrong while fetching data!!!");
	    	$scope.gridOptionsOrgView.data = [];
	    });
	};
	
	function showAlert(message) {
		$mdDialog.show($mdDialog.alert().parent(
				angular.element(document.querySelector('#popupContainer')))
				.clickOutsideToClose(true).textContent(message).ariaLabel(
						'Alert Dialog').ok('Ok'));
	}
	
	$scope.assignRole = function(action, userData){
		$('#home').addClass('md-scroll-mask');
		userData.action = action;
		$mdDialog.show({
		      controller: AddRoleController,
		      templateUrl: 'templates/newRoleTemplate.html',
		      parent: angular.element(document.body),
		      clickOutsideToClose:false,
		      locals:{dataToPass: userData, gridOptionsData: $scope.gridOptions.data},
		    })
		    .then(function(result) {
		    	if(result == "Add") showAlert('Role assigned successfully');
		    	else if(result == "Update") showAlert('Role updated successfully');
		    	else if(result == "Cancelled") console.log(result);
		    	else showAlert('Role assigning/updation failed!!!');
		    });
	};
	
	$scope.cancel = function() {
		$mdDialog.hide();
		};
	$scope.deleteRole = function(row){
		$('#home').addClass('md-scroll-mask');
	    var confirm = $mdDialog.confirm()
	    	  .clickOutsideToClose(true)
	          .textContent('Are you sure want to delete the role?')
	          .ok('Ok')
	          .cancel('Cancel');
	    $mdDialog.show(confirm).then(function() {
			deleteUserRole(row.entity.employeeId);
			$timeout(function(){updateGridAfterDelete(row)},500);
	    }, function() {
	    	console.log("Cancelled dialog");
	    });
	};
	function deleteUserRole(empId){
		var req = {
				method : 'DELETE',
				url : appConfig.appUri+ "user/deleteEmployee?empId="+empId
			}
			$http(req).then(function mySuccess(response) {
				$scope.result = response.data;
				console.log($scope.result);
			}, function myError(response){
				$scope.result = "Error";
			});
	}
	
	function updateGridAfterDelete(row){
		if($scope.result == "Success" || $scope.result == ""){
			var index = $scope.gridOptions.data.indexOf(row.entity);
			$scope.gridOptions.data.splice(index, 1);
			showAlert('Role deleted successfully');
		}else if($scope.result == "Error"){
			showAlert('Something went wrong while deleting the role.')
		}
    	
	}
	
	function AddRoleController($scope, $mdDialog, dataToPass, gridOptionsData) {
		$scope.templateTitle = dataToPass.action;
		$scope.alertMsg = "";
		$scope.isDisabled = false;
		$scope.result = "";
		if(dataToPass.action == "Add"){
			$scope.empId = "";
			$scope.empName = "";
			$scope.gender = "";
			$scope.empRole;
			$scope.empEmail = "";
			$scope.empLocation = "";
			$scope.functionalGroup = "";
			$scope.empStatus = "";
			$scope.employmentType = "";
			$scope.designation = "";
			$scope.domain = "";
			$scope.isDisabled = false;
			$scope.hasPassort = "";
			$scope.hasB1 = "";
		}else if(dataToPass.action == "Update") {
			$scope.empId = dataToPass.employeeId;
			$scope.empName = dataToPass.employeeName;
			$scope.gender = dataToPass.gender;
			$scope.empRole = dataToPass.role;
			$scope.empEmail = dataToPass.emailId;
			$scope.empLocation = dataToPass.empLocation;
			$scope.functionalGroup = dataToPass.functionalGroup;
			$scope.empStatus = dataToPass.empStatus;
			$scope.employmentType = dataToPass.employmentType;
			$scope.domain = dataToPass.domain;
			$scope.designation = dataToPass.designation;
			$scope.dateOfJoining =  new Date(dataToPass.dateOfJoining);
			$scope.dateOfBirth =  new Date(dataToPass.dateOfBirth);
			$scope.isDisabled = true;
			$scope.hasPassort = dataToPass.hasPassort;
			$scope.hasB1 = dataToPass.hasB1;
			$scope.passportExpiryDate =  new Date(dataToPass.passportExpiryDate);
			$scope.b1ExpiryDate =  new Date(dataToPass.b1ExpiryDate);
		}
		$scope.domains = myFactory.getDomains();
		$scope.roles = myFactory.getRoles();
		$scope.locations=myFactory.getLocations();
		$scope.designations=myFactory.getDesignations();
		$scope.functionalGroups=myFactory.getFunctionalgroups();
		$scope.employmentTypes=myFactory.getEmployementTypes();
		$scope.empStatuses=myFactory.getEmployeeStatus();
		$scope.getSelectedRole = function(){
			if ($scope.empRole !== undefined) {
				return $scope.empRole;
			} else {
				return "Please select a role";
			}
		};
		$scope.getSelectedLocation = function(){
			if ($scope.empLocation !== undefined) {
				return $scope.empLocation;
			} else {
				return "Please select a location";
			}
		};
		$scope.getDesignationText = function(){
			if ($scope.designation !== undefined) {
				return $scope.designation;
			} else {
				return "Please select a designation";
			}
		};
		$scope.getSelectedFunctionalGroup = function(){
			if ($scope.functionalGroup !== undefined) {
				return $scope.functionalGroup;
			} else {
				return "Please select a Functional Org";
			}
		};
		$scope.getSelectedEmploymentType = function(){
			if ($scope.employmentType !== undefined) {
				return $scope.employmentType;
			} else {
				return "Please select a Employment Type";
			}
		};
		$scope.getSelectedDomain = function(){
			if ($scope.domain !== undefined) {
				return $scope.domain;
			} else {
				return "Please select a Domain";
			}
		};
		$scope.getSelectedEmpStatus = function(){
			if ($scope.empStatus !== undefined) {
				return $scope.empStatus;
			} else {
				return "Please select a employee status";
			}
		};
		$scope.getSelectedGender = function() {
			if ($scope.gender !== undefined) {
				return $scope.gender;
			} else {
				return "Please select a Gender";
			}
		};
			
		
		function checkRoleEmpIdRange(searchId){
			return parseInt(searchId) >= appConfig.empStartId && parseInt(searchId) <= appConfig.empEndId;
		}
		
		function checkRoleExistence(searchId){
			for(var i in gridOptionsData){
				if(gridOptionsData[i].employeeId == searchId){
					return true;
				}
			}
			return false;
		}
		
		$scope.validateEmailId = function(){
			var emailId = $scope.empEmail;
			if(emailId != "" && !validateEmail(emailId)){
				$scope.alertMsg = "Please enter a valid nisum email id";
				document.getElementById('empEmail').focus();
			}else{
				$scope.alertMsg = "";
			}
		}
		
		function validateEmail(emailId){
			 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			 if(re.test(emailId)){
		        if(emailId.indexOf("@nisum.com", emailId.length - "@nisum.com".length) !== -1){
		        	return true;
		        }
			 }
			 return false;
		 }
		
		$scope.validateFields = function(){
			var searchId = $scope.empId;
			var empName = $scope.empName;
			var gender = $scope.gender;
			var empRole = $scope.empRole;
			var empEmail = $scope.empEmail;
			if(searchId == ""){
				$scope.alertMsg = "Employee ID is mandatory";
				document.getElementById('empId').focus();
			}else if(searchId != "" && !checkRoleEmpIdRange(searchId)){
				$scope.alertMsg = 'Employee ID should be in between '+appConfig.empStartId+' - '+appConfig.empEndId;
				document.getElementById('empId').focus();
			}else if(searchId != "" && checkRoleExistence(searchId) && $scope.templateTitle == "Add"){
				$scope.alertMsg = 'Employee ID is already assigned a role';
				document.getElementById('empId').focus();
			}else if(empName == ""){
				$scope.alertMsg = "Employee Name is mandatory";
				document.getElementById('empName').focus();
			}else if(gender == "") {
				$scope.alertMsg = "Gender is mandatory";
				document.getElementById('gender').focus();
			}else if(empEmail == "") {
				$scope.alertMsg = "Email ID is mandatory";
				document.getElementById('empEmail').focus();
			}else if(empRole == undefined){
				$scope.alertMsg = "Please select a role";
				document.getElementById('empRole').focus();
			}else{
				$scope.alertMsg = "";
				console.log($scope.empName,"VENU");
				var record = {"employeeId":$scope.empId, "employeeName": $scope.empName, "gender": $scope.gender,"emailId": $scope.empEmail, 
						"role": $scope.empRole, "empLocation": $scope.empLocation,"designation": $scope.designation,"functionalGroup": $scope.functionalGroup,
						"empStatus": $scope.empStatus,"employmentType": $scope.employmentType,"domain": $scope.domain,"dateOfJoining":$scope.dateOfJoining,
						"dateOfBirth":$scope.dateOfBirth,"hasPassort":$scope.hasPassort,"hasB1":$scope.hasB1,"passportExpiryDate":$scope.passportExpiryDate,
						"b1ExpiryDate":$scope.b1ExpiryDate
						};
				
				addOrUpdateRole(record, $scope.templateTitle);
				$timeout(function(){updateGrid($scope.templateTitle, record)},500);
			}
		};
		
		$scope.cancel = function() {
			if(this.myForm.$dirty){
				$mdDialog.show($mdDialog.confirm({
					skipHide: true,
					textContent: 'Are you sure you want to cancel this?',
					ok: 'ok',
					cancel:'cancel'
				  })).then(function(){
					  $mdDialog.hide('Cancelled');
			})
				}
				else{
					$mdDialog.hide('Cancelled'); 
				}
		};
		function updateGrid(action, record){
			if($scope.alertMsg == ""){
				if($scope.result == "Success"){
					if(action == "Add"){
						gridOptionsData.push(record);
					}else if(action == "Update"){
						var existingRecord = getRowEntity($scope.empId);
						var index = gridOptionsData.indexOf(existingRecord);
						gridOptionsData[index] = record;
					}
					$mdDialog.hide(action);
				}else{
					$mdDialog.hide("Error");
				}
				
			}
		}
		
		function addOrUpdateRole(record, action){
			var urlRequest  = "";
			if(action == "Add"){
				urlRequest = appConfig.appUri+ "user/assignEmployeeRole";
			}else if(action == "Update"){
				urlRequest = appConfig.appUri+ "user/updateEmployeeRole";
			}
			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 getRowEntity(empId){
			for(var i=0;i<gridOptionsData.length;i++){
				var record = gridOptionsData[i];
				if(record.employeeId == empId){
					return record;
				}
			}
		}
	}
});