'use strict';

angular.module('myApp.workOrderCycleTime', ['ngRoute'])

.run(['directiveService', function(directiveService){
	directiveService.addFullComponent({
		tag: function(){return 'work-order-cycle-time';},
		configTag: function(){return 'work-order-cycle-time-config'},
		tagHtml:
function(){"<work-order-cycle-time></work-order-cycle-time>";},
		directiveName: function(){return 'workOrderCycleTime';},
		namespace: function(){'workorder'},
		paletteImage: function(){return 'clock.png';}
	});
}])

.factory('workOrderCycleTimeDataService', ['$http',
'workOrderCycleTimeSharedProperties', function($http,
workOrderCycleTimeSharedProperties){
	/*set up some function to query for data.  not unlike
	 *  you've already done.  consider a default organization 
	 *  to populate the graph along with a config button which
	 *  opens up a modal view.  Within that modal, consider all user
	 *  configurable parameters which can be set in this modal.  have the
chart 
	 *  draw (or redraw) on click of "OK" button.*/
	var serviceObject = {};
	var _getWorkOrderData = function(){
		var organization = "DEU";
		
		var today = new Date();
		var someTimeBefore = new Date(today.getFullYear()-1, today.getMonth(),
today.getDate());
		
		if(workOrderCycleTimeSharedProperties.getOrganization() != null){
			organization = workOrderCycleTimeSharedProperties.getOrganization();
		}
		
		if(workOrderCycleTimeSharedProperties.getStartDate() != null){
			someTimeBefore = new
Date(workOrderCycleTimeSharedProperties.getStartDate());
		}
		
		if(workOrderCycleTimeSharedProperties.getEndDate() != null){
			today = new Date(workOrderCycleTimeSharedProperties.getEndDate());
		}
		
		workOrderCycleTimeSharedProperties.setStartDate(someTimeBefore);
		workOrderCycleTimeSharedProperties.setEndDate(today);
		
		var mongoUrl =
"http://10.239.3.132:9763/MongoServlet-0.0.1-SNAPSHOT/send";
		var requestString = "{\"createdTime\" : {\"$gt\" : { \"$date\":
\""+someTimeBefore.toJSON()+"\" }, \"$lt\": { \"$date\":
\""+today.toJSON()+"\" }}, \"organization\" : \""+organization+"\"}";
		var config = {
				method: 'POST',
				headers: {'Collection' : 'Event'},
				url: mongoUrl,
				data: requestString
		};
		return $http(config);
	}
	serviceObject = {
			getWorkOrderData : _getWorkOrderData
	}
	return serviceObject;
}])

.factory('workOrderCycleTimeSharedProperties', [function(){
	var _organization = "DEU";
	var _render;
	
	//var _startDate = new Date();
	//var _endDate= new Date(_startDate.getFullYear-1,
_startDate.getMonth(), _startDate.getDate());
	
	var _startDate = null;
	var _endDate = null;
	
	var _setStartDate = function(start){
		_startDate = start;
	}
	
	var _getStartDate = function(){
		return _startDate;
	}
	
	var _setEndDate = function(end){
		_endDate = end;
	}
	
	var _getEndDate = function(){
		return _endDate;
	}
	
	var _getStartDate = function(){
		return _startDate;
	}
	
	var _setRender = function(render){
		_render = render;
	}
	
	var _getRender = function(){
		return _render;
	}
	
	var _setOrganization = function(organization){
		_organization = organization;		
	}
	
	var _getOrganization = function(){
		return _organization;
	}
	var _serviceObj = {
			setEndDate : _setEndDate,
			getEndDate : _getEndDate,
			setStartDate : _setStartDate,
			getStartDate : _getStartDate,
			getOrganization : _getOrganization,
			setOrganization : _setOrganization,
			getRender : _getRender,
			setRender : _setRender
	};
	return _serviceObj;
}])

.controller('workOrderCycleTimeConfigCtrl', ['$scope', '$modalInstance',
'findOrganizationService', 'workOrderCycleTimeSharedProperties',
function($scope, $modalInstance, findOrganizationService,
workOrderCycleTimeSharedProperties){
	findOrganizationService.promise.then(function(response){
		$scope.responseData = response.data.result;		
		var organizationNames = [];
		for(var i=0;i<$scope.responseData.length;i++) {
			if(organizationNames.indexOf($scope.responseData[i].organization) ==
-1) {
				organizationNames.push($scope.responseData[i].organization);
			}
		}
		$scope.organizationNames = organizationNames;
	});
	$scope.endDate = workOrderCycleTimeSharedProperties.getEndDate();
	$scope.startDate = workOrderCycleTimeSharedProperties.getStartDate();
	$scope.previousOrganization =
workOrderCycleTimeSharedProperties.getOrganization();
	$scope.changeOrganization = function(organizationName){
		workOrderCycleTimeSharedProperties.setOrganization(organizationName);
	}
	$scope.ok = function(){
		$modalInstance.dismiss('cancel');
		var renderChart = workOrderCycleTimeSharedProperties.getRender();
		workOrderCycleTimeSharedProperties.setEndDate($scope.endDate);
		workOrderCycleTimeSharedProperties.setStartDate($scope.startDate);
		renderChart();
	}
	$scope.cancel = function(){
		workOrderCycleTimeSharedProperties.setOrganization($scope.previousOrganization);
		$modalInstance.dismiss('cancel');
	}
}])

.controller('workOrderCycleTimeCtrl', ['$scope', '$modal',
'workOrderCycleTimeDataService', 'findOrganizationService',
'workOrderCycleTimeSharedProperties', function($scope, $modal,
workOrderCycleTimeDataService, findOrganizationService,
workOrderCycleTimeSharedProperties){
	var eventData = [];
	
	$scope.drawChartNow = false;
	$scope.showAsset = false;
	
	findOrganizationService.promise.then(function(response){
		$scope.responseData = response.data.result;
		var organizationNames = [];
		for(var i=0;i<$scope.responseData.length;i++) {
			if(organizationNames.indexOf($scope.responseData[i].organization) ==
-1) {
				organizationNames.push($scope.responseData[i].organization);
			}
		}
		$scope.organizationNames = organizationNames;
	});
	
	$scope.renderChart = function() {
		$scope.drawChartNow = false;
		$scope.showAsset = false;
		workOrderCycleTimeDataService.getWorkOrderData().success(function(data){
			eventData = data.result;
			if(eventData==null){alert("What the fuck?");return;}
			angular.forEach(data.result, function(data){
				var createdTime = new Date(data.createdTime);
				var closedTime = new Date();
				if(data.status === "Closed"){
					closedTime = new Date(data.closedTime);
				}
				data.daysOpen = Math.abs((closedTime -
createdTime)/(1000*60*60*24));
			});
			$scope.cycleData = crossfilter(data.result);
		})
		.error(function(){
			console.log("The server is down.");
		})
		.finally(function(){
			
			//define x-axis min/max
			$scope.startDate = new
Date(workOrderCycleTimeSharedProperties.getStartDate());
			$scope.endDate = new
Date(workOrderCycleTimeSharedProperties.getEndDate());
			
			$scope.organizationName =
workOrderCycleTimeSharedProperties.getOrganization();
			
			//define all dimensions
			var monthDimension = $scope.cycleData.dimension(function(d){
				return d3.time.month(new Date(d.closedTime));
			});
			$scope.monthDimension = monthDimension;
			var organizationDimension = $scope.cycleData.dimension(function(d){
				return d.organization;
			});
			$scope.organizationDimension = organizationDimension;
			var facilityDimension = $scope.cycleData.dimension(function(d){
				return d.facility;
			});
			$scope.facilityDimension = facilityDimension;
			var assetDimension = $scope.cycleData.dimension(function(d){
				return d.asset;
			});
			$scope.assetDimension = assetDimension;
			
			
			//define all groups.  need to replace reduceSum with 
			//generic reduce which averages the number of days open
			
			/*var wasteGroup = monthDimension.group().reduceSum(function(d){
				return d.daysOpen;
			});
			$scope.wasteGroup = wasteGroup;
			var orgWasteGroup =
organizationDimension.group().reduceSum(function(d){
				return d.daysOpen;
			});
			$scope.orgWasteGroup = orgWasteGroup;
			var facilityWasteGroup =
facilityDimension.group().reduceSum(function(d){
				return d.daysOpen;
			});
			$scope.facilityWasteGroup = facilityWasteGroup;
			var assetWasteGroup = assetDimension.group().reduceSum(function(d){
				return d.daysOpen;
			});
			$scope.assetWasteGroup = assetWasteGroup;*/
			
			var wasteGroup = monthDimension.group().reduce(
					function(p,d){
						p.count += 1;
						p.sum += d.daysOpen;
						if(p.count == 0){
							p.avg = 0;
						}
						else{
							p.avg = p.sum / p.count;
						}
						return p;
					},
					function(p,d){
						p.count -= 1;
						p.sum -= d.daysOpen;
						if(p.count == 0){
							p.avg = 0;
						}
						else{
							p.avg = p.sum / p.count;
						}
						return p;
					},
					function(){
						return {
							count:0 ,
							sum: 0,
							avg: 0
						};
					}
			);
			$scope.wasteGroup = wasteGroup;
			
			var orgWasteGroup = organizationDimension.group().reduce(
					function(p,d){
						p.count += 1;
						p.sum += d.daysOpen;
						if(p.count == 0){
							p.avg = 0;
						}
						else{
							p.avg = p.sum / p.count;
						}
						return p;
					},
					function(p,d){
						p.count -= 1;
						p.sum -= d.daysOpen;
						if(p.count == 0){
							p.avg = 0;
						}
						else{
							p.avg = p.sum / p.count;
						}
						return p;
					},
					function(){
						return {
							count: 0,
							sum: 0,
							avg: 0
						};
					}
			);
			$scope.orgWasteGroup = orgWasteGroup;
			
			var facilityWasteGroup = facilityDimension.group().reduce(
					function(p,d){
						p.count += 1;
						p.sum += d.daysOpen;
						if(p.count == 0){
							p.avg = 0;
						}
						else{
							p.avg = p.sum / p.count;
						}
						return p;
					},
					function(p,d){
						p.count -= 1;
						p.sum -= d.daysOpen;
						if(p.count == 0){
							p.avg = 0;
						}
						else{
							p.avg = p.sum / p.count;
						}
						return p;
					},
					function(){
						return {
							count: 0,
							sum: 0,
							avg: 0
						};
					}
			);
			$scope.facilityWasteGroup = facilityWasteGroup;
			
			var assetWasteGroup = assetDimension.group().reduce(
					function(p,d){
						p.count += 1;
						p.sum += d.daysOpen;
						p.avg = p.sum / p.count;
						return p;
					},
					function(p,d){
						p.count -= 1;
						p.sum -= d.daysOpen;
						if(p.count == 0){
							p.avg = 0;
						}
						else{
							p.avg = p.sum / p.count;
						}
						return p;
					},
					function(){
						return {
							count: 0,
							sum: 0,
							avg: 0
						};
					}
			);
			
			$scope.assetWasteGroup = assetWasteGroup;
			
			$scope.valueAccess = function(p){
				return p.value.avg;
			}
			$scope.barTitleFormat = function(p){
				var months = ["January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December"];
				return "Organization: "+$scope.organizationName+"\nMonth:
"+months[p.key.getMonth()]+"\nAvg Days to Close:
"+Math.round(p.value.avg*10)/10;
			}
			$scope.facilityTitleFormat = function(p){
				return "Facility: "+p.key+"\nAvg Days To Close:
"+Math.round(p.value.avg*10)/10;
			}
			$scope.assetTitleFormat = function(p){
				return "Asset: "+p.key+"\nAvg Days To Close:
"+Math.round(p.value.avg*10)/10;
			}
			$scope.drawChartNow = true;		
		})
	};
	$scope.renderChart();
	workOrderCycleTimeSharedProperties.setRender($scope.renderChart);
	
	$scope.resetDates = function(){
		$scope.endDate = new Date();
		$scope.startDate = new Date($scope.endDate.getFullYear()-1,
$scope.endDate.getMonth(), $scope.endDate.getDate());
		workOrderCycleTimeSharedProperties.setStartDate($scope.startDate);
		workOrderCycleTimeSharedProperties.setEndDate($scope.endDate);
	}
	
	$scope.renderAssetChart = function(){
		$scope.showAsset = !$scope.showAsset;
	}
	$scope.open = function(size){
		var modalInstance = $modal.open({
			templateUrl : 'views/workOrderCycleTimeConfig.html',
			controller : 'workOrderCycleTimeConfigCtrl',
			scope : $scope,
			size : size,
		})
	}
}])

.directive('workOrderCycleTime', [function(){
	return {
		restrict: 'E',
		controller: 'workOrderCycleTimeCtrl',
		templateUrl: 'views/workOrderCycleTime.html',
	}
}])































work order cycle time: uploading files for work order cycle time gal
2021 widget
Made changes to app.js and index.html for work order cycle time widget.
updated the add axis button to accurately reflect spacing as a result of
adding axis.  removed the automatic right axis on the composite chart
changed the interface/buttons to allow for a slightly cleaner adding
axis/points to axis functionality.  not finished
fixed bug which would allow the 'add axis' function to draw axis on
incorrect charts
Merge branch 'master' of https://github.com/philpci/ui.git
work order cycle time: eliminated conflicts caused by using shared
properties when working with multiple instances f the component on a
dashboard.
updated to current work version
added extra buttons for editing existing axis.  currently non-functional
started adding code to add label to created axis.  currently not 100%
functional, still have an issue with spacing.
partially fixed axis spacing.  still needs work to prevent wasted white
space
Merge branch 'master' of http://phil@10.239.3.132:9763/gitblit/r/galaxy2021.git