myApp.controller("domainController",
	function($scope, myFactory, exportUiGridService, $mdDialog,$http, appConfig, $timeout, $window, $mdSelect) {
		$scope.records = [];
		$scope.empSearchId = "";
		$scope.parentData = {};
		$scope.isDisabled = false;

		$window.addEventListener('click', function(e) {
			if (e.target.type !== 'search') {
				$mdSelect.hide();
			}

		});

		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="Edit" 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 : 10,
			pageNumber : 1,
			pageSize : 10,
			enableFiltering : true,
			columnDefs : [
					{
						field : 'domainId',
						displayName : 'Domain ID',
						enableColumnMenu : false,
						enableSorting : true,
						enableFiltering : true,
						width : 120,
					},
					{
						field : 'domainName',
						displayName : 'Domain',
						enableColumnMenu : false,
						enableSorting : true,
						enableFiltering : true
					},
					{
						field : 'accountName',
						displayName : 'Account ',
						enableColumnMenu : false,
						enableSorting : true,
						enableFiltering : true
					},
					{
						field : 'deliveryManagers',
						displayName : 'Delivery Leads',
						cellTemplate : '<div ng-repeat= "deliveryManager in row.entity[col.field]">{{deliveryManager.employeeName}}<span ng-hide="$last">,</span></div>',
						enableColumnMenu : false,
						enableSorting : true,
						enableFiltering : true
					}, {
						field : 'status',
						displayName : 'Status ',
						enableColumnMenu : false,
						enableSorting : true,
						enableFiltering : true
					}, {
						name : 'Actions',
						displayName : 'Actions',
						cellTemplate : getCellTemplate,
						enableColumnMenu : false,
						enableSorting : false,
						enableFiltering : false,
						width : 130
					}

			]
		};

		$scope.getRowData = function(row, action) {
			$scope.parentData.id = row.entity._id;
			$scope.parentData.domainId = row.entity.domainId;
			$scope.parentData.domainName = row.entity.domainName;
			$scope.parentData.account = row.entity.accountName;
			$scope.parentData.deliveryManagers = row.entity.deliveryManagers;

			if (action == "Update")
				$scope.addDomain(action, $scope.parentData);
			else if (action == "Delete")
				$scope.deleteDomain(row);
		}
		$scope.records = [];
		$scope.alertMsg = "";
		$scope.gridOptions.data = $scope.records;

		$scope.getEmployeesToTeam = function() {
			$http(
					{
						method : "GET",
						url : appConfig.appUri
								+ "/projectTeam/getEmployeesToTeam"
					})
					.then(
							function mySuccess(response) {
								$scope.employees = response.data;

							},
							function myError(response) {
								showAlert("Something went wrong while fetching data!!!");
								$scope.gridOptions.data = [];
							});
		};

		function showAlert(message) {
			$mdDialog.show($mdDialog.alert().parent(
					angular.element(document
							.querySelector('#popupContainer')))
					.clickOutsideToClose(true).textContent(message)
					.ariaLabel('Alert Dialog').ok('Ok'));
		}

		$scope.getDomains = function() {
			$http({
				method : "GET",
				url : appConfig.appUri + "/domains"
			})
					.then(
							function mySuccess(response) {
								console.log(response.data);
								$scope.gridOptions.data = response.data;
							},
							function myError(response) {
								showAlert("Something went wrong while fetching data!!!");
							});
		};

		function refreshPage() {
			$scope.getDomains();
		}

		$scope.addDomain = function(action, userData) {
			$('#home').addClass('md-scroll-mask');
			userData.action = action;
			$mdDialog
					.show(
							{
								controller : AddDomainController,
								templateUrl : 'templates/newDomain.html',
								parent : angular
										.element(document.body),
								clickOutsideToClose : false,
								locals : {
									dataToPass : userData,
									gridOptionsData : $scope.gridOptions.data,
									employees : $scope.employees
								},
							})
					.then(
							function(result) {
								if (result == "Add") {
									showAlert('Domain created successfully');
								} else if (result == "Update") {
									showAlert('Domain updated successfully');
								} else if (result == "Cancelled")
									console.log(result);
								else
									showAlert('Domain assigning/updation failed!!!');
							});
		};

		$scope.deleteDomain = function(row) {
			$('#home').addClass('md-scroll-mask');
			var confirm = $mdDialog.confirm().clickOutsideToClose(
					true).textContent(
					'Are you sure want to Inactive this Domain?').ok(
					'Ok').cancel('Cancel');
			$mdDialog.show(confirm).then(function() {
				deleteDomainRow(row.entity.domainId);
				showAlert("Domain Inactived successfully");
			}, function() {
				console.log("Cancelled dialog");
			});
		};

		function deleteDomainRow(domainId) {
			var req = {
				method : 'DELETE',
				url : appConfig.appUri + "/domains?domainId="
						+ domainId
			}
			$http(req).then(function mySuccess(response) {
				refreshPage();
			}, function myError(response) {
				$scope.result = "Error";
			});
		}
		function updateGrid(action, result) {
			if ($scope.alertMsg == "") {
				if (result == "Success") {
					if (action == "Add") {
						refreshPage();
					} else if (action == "Update") {
						refreshPage();
					}
					$mdDialog.hide(action);
				} else {
					$mdDialog.hide("Error");
				}
			}
		}

		function AddDomainController($scope, $mdDialog, dataToPass,gridOptionsData, employees) {

			console.log("employees", employees);
			$scope.searchTerm = "";
			$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.clearSearchTerm = function() {
				$scope.searchTerm = '';
			};
			$('input').on('keydown', function(ev) {

				ev.stopPropagation();

			});

			$scope.employeeList = employees;
			$scope.employeeNamesArray = [];
			$scope.employeeModel;
			$scope.templateTitle = dataToPass.action;

			$scope.accounts = myFactory.getAccounts();

			$scope.getSelectedText = function() {

				if ($scope.employeeModel !== undefined) {

					return null;

				} else {
					return "Please select a Delivery Head";

				}

			}

			$scope.getAccountText = function() {

				if ($scope.account !== undefined) {
					return $scope.account.accountName;
				}

				else {
					return "Please select account";
				}
			};

			$scope.cancel = function() {
				$mdDialog.hide('Cancelled');
			};

			$scope.deliveryHeads = function() {
				var length = $scope.employeeModel.length;
				console.log(length);
				for (i = 0; i < length; i++) {
					$scope.employeeNamesArray[i] = $scope.employeeModel[i].employeeId;
				}
				return $scope.employeeNamesArray;

			}

			$scope.removeSelectedLead = function(item) {
				var index = $scope.employeeModel.indexOf(item);
				console.log(index);
				$scope.employeeNamesArray.splice(index, 1);
				$scope.employeeModel.splice(index, 1);
				console.log($scope.employeeNamesArray);

			}

			function updatingGridBasedOnStatus(status, response,result) {
				if (response == "Domain saved succesfully") {
					updateGrid("Add", result);
				} else if (response == "Domain updated successfully") {
					updateGrid("Update", result);
				} else if (response == "Domain already exists") {
					 $scope.alertMsg = "Domain already exist,Please enter new matching";
				}

			}

			$scope.addOrUpdateDomain = function(record,action) {
				if(action == "Update"){
					methodType = "PUT";
				}
				else if(action == "Add"){
					methodType = "POST"
				}
				$http({
					method : methodType,
					url : appConfig.appUri + "/domains",
					headers : {
						"Content-type" : "application/json"
					},
					data : record
				})
						.then(
								function mySuccess(response) {
									$scope.result = "Success";
									console.log(response);
									updatingGridBasedOnStatus(dataToPass.action,response.data,$scope.result);
								},
								function myError(response) {
									showAlert("Something went wrong while fetching data!!!");
								});
			}
			if (dataToPass.action == "Add") {
				$scope.domainName = "";
				$scope.accountName = "";
				$scope.deliveryManagers = "";
			} else if (dataToPass.action == "Update") {
				$scope.isDisabled = true;
				$scope.id = dataToPass.id;
				$scope.domainId = dataToPass.domainId;
				$scope.domainName = dataToPass.domainName;
				$scope.account = {};
				$scope.account.accountName = dataToPass.account;
				$scope.employeeModel = dataToPass.deliveryManagers;
			}
			$scope.validateFields = function(action){
				var domainId = $scope.domainId;
				var AccountName = $scope.account;
				var domainName = $scope.domainName;
				var deliveryManagers = $scope.employeeModel;
				if(action == "Add"){
				
					if(AccountName == undefined){
						$scope.alertMsg = "Please select a Account";
					document.getElementById('account').focus();
					}else if(domainName == undefined){
						$scope.alertMsg = "Please enter a Domain Name";
						document.getElementById('domainName').focus();
					}else if(deliveryManagers == undefined){
						$scope.alertMsg = "Please select a deliveryManagers";
						document.getElementById('selectDeliveryLeads').focus();
					}else {
						$scope.alertMsg = "";
						var record = {
								"domainName" : $scope.domainName,
								"accountName" : $scope.account.accountName,
								"deliveryManagers" : $scope.deliveryHeads()
							};
						$scope.addOrUpdateDomain(record,action);
					}
				}else{
					$scope.alertMsg = "";
					var AccountName = $scope.account.accountName;
					var domainName = $scope.domainName;
					var deliveryManagers1 = $scope.deliveryHeads();
					if(AccountName == undefined){
						$scope.alertMsg = "Please select a Account";
					document.getElementById('account').focus();
					}else if(domainName == "" || undefined) {
						$scope.alertMsg = "Please enter a Domain Name";
						document.getElementById('domainName').focus();
					}else if(deliveryManagers.length <= 0){
						$scope.alertMsg = "Please select a deliveryManagers";
						document.getElementById('selectDeliveryLeads').focus();
					}else {
						$scope.alertMsg = "";
						var record = {
								"domainName" : $scope.domainName,
								"accountName" : $scope.account.accountName,
								"deliveryManagers" : $scope.deliveryHeads(),
								"id" : $scope.id,
						        "domainId" : dataToPass.domainId
							};
						$scope.addOrUpdateDomain(record,action);
					}
				}
				
				
			};
		}

	});