var StatsModule = angular.module('StatsModule', []);

StatsModule.config(['$routeProvider', function ($routeProvider) {

	$routeProvider.when('/stats/', {
		controller: 'StatsMainCtrl',
		templateUrl: 'stats/overview.html'
	});

	$routeProvider.when('/stats/repairs', {
		controller: 'StatsRepairsCtrl',
		templateUrl: 'stats/repairs.html'
	});

	$routeProvider.when('/stats/user/:userId', {
		controller: 'StatsUserCtrl',
		templateUrl: 'stats/user.html'
	});

	$routeProvider.when('/stats/clients', {
		controller: 'StatsClientsCtrl',
		templateUrl: 'stats/clients.html'
	});

}]);

StatsModule.factory('UserTarget', function () {
	return {
		getCssClass: function (percentage) {
			if (percentage < 50)
				return 'bar-danger';
			else if (percentage < 85)
				return 'bar-warning';
			else
				return 'bar-success';
		}
	};
});

StatsModule.service('StatsHelpers', function () {

	this.dates = {
		startDate: moment().subtract('month', 1).set('date', 28),
		endDate: moment().set('date', 27)
	};

	this.daterangepicker = {
		ranges: {
			'Today': [moment(), moment()],
			'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
			'Last 7 Days': [moment().subtract('days', 6), moment()],
			'Last 30 Days': [moment().subtract('days', 29), moment()],
			'This Month': [moment().startOf('month'), moment().endOf('month')],
			'Payroll': [moment().subtract('month', 1).set('date', 28), moment().set('date', 27)],
			'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
		},
		locale: {
			firstDay: 1 // Monday is the first day of the week
		}
	};

});
StatsModule.controller('StatsClientsCtrl', ['$scope', '$http', 'ErrorsHandler', 'apiUrl', function ($scope, $http, ErrorsHandler, apiUrl) {

	$scope.data = [];

	$scope.dates = {
		startDate: moment().startOf('month'),
		endDate: moment().endOf('month')
	};

	$scope.daterangepicker = {
		ranges: {
			'This Month': [moment().startOf('month'), moment().endOf('month')],
			'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')],
			'Month before last': [moment().subtract('month', 2).startOf('month'), moment().subtract('month', 2).endOf('month')]
		},
		locale: {
			firstDay: 1 // Monday is the first day of the week
		}
	};

	$scope.$watch('dates', function () {
		$scope.load();
	});

	$scope.load = function () {
		$http.get(apiUrl('stats/clients/activity'), { params: { start_date: $scope.dates.startDate.format('X'), end_date: $scope.dates.endDate.format('X') } })
			.success(function (response) {
				$scope.data = response;
			})
			.error(ErrorsHandler);
	};
}]);

StatsModule.controller('StatsMainCtrl', ['$scope', '$location', 'TaskFeedback', 'StatsHelpers', function ($scope, $location, TaskFeedback, StatsHelpers) {

	if ($location.path() == '') {
		$location.path('/stats');
		return;
	}

	$scope.helpers = StatsHelpers;

}]);
StatsModule.controller('StatsRepairsCtrl', ['$scope', '$http', 'apiUrl', 'StatsHelpers', function ($scope, $http, apiUrl, StatsHelpers) {

	$scope.helpers = StatsHelpers;

	$scope.income = {};
	$scope.overview = {};

	$scope.dailyLineChart = {
		data: [],
		series: ['Booked In', 'Fixed'],
		labels: []
	};

	var joinAxisResults = function (data1, data2) {
		// First we need to combine the booked & completed into a single array
		var rows = [];

		_.each(data1, function (el) {
			rows.push({
				"c": [{ v: el.date }, { v: parseInt(el.total, 10) }, { v: 0 }]
			});
		});

		// Now this is more complicated because this time we will need to check
		// if an entry with the given date exists and if so we will have to modify it
		// otherwise create a new entry
		_.each(data2, function (el) {
			// We are first looking to see if a record for the given date exists
			var entry = _.find(rows, function (item) { return item.c[0].v == el.date; });

			if (entry) {
				entry.c[2].v = parseInt(el.total, 10);
			}
			else {
				rows.push({
					"c": [{ v: el.date }, { v: 0 }, { v: parseInt(el.total, 10) }]
				});
			}
		});

		// Sort by date
		rows = _.sortBy(rows, function (el) { return el.c[0].v; });

		return rows;
	};

	$scope.loadIncome = function () {
		$http.get(apiUrl('stats/repairs/income'), { params: { start_date: StatsHelpers.dates.startDate.format('X'), end_date: StatsHelpers.dates.endDate.format('X') } })
			.success(function (response) {
				$scope.income = response;
			});
	};

	$scope.loadOverview = function () {
		$http.get(apiUrl('stats/repairs/overview'), { params: { start_date: StatsHelpers.dates.startDate.format('X'), end_date: StatsHelpers.dates.endDate.format('X') } })
			.success(function (response) {
				$scope.overview = response;
			});
	};

	$scope.loadDailyStats = function () {
		$http.get(apiUrl('stats/repairs/daily-summary'), { params: { start_date: StatsHelpers.dates.startDate.format('X'), end_date: StatsHelpers.dates.endDate.format('X') } }).success(function (response) {
			var data = joinAxisResults(response.booked, response.completed);

			$scope.dailyLineChart.data = [[], []];
			$scope.dailyLineChart.labels = [];

			_.each(data, function (item) {
				$scope.dailyLineChart.labels.push(item.c[0].v);
				$scope.dailyLineChart.data[0].push(item.c[1].v);
				$scope.dailyLineChart.data[1].push(item.c[2].v);
			});
		});
	};

	$scope.$watch('helpers.dates', function () {
		$scope.loadDailyStats();
		$scope.loadIncome();
		$scope.loadOverview();
	});

}]);

StatsModule.controller('StatsUserCtrl', ['$scope', 'User', 'ErrorsHandler', '$routeParams', 'apiUrl', '$http', 'UserTarget', 'StatsHelpers', function ($scope, User, ErrorsHandler, $routeParams, apiUrl, $http, UserTarget, StatsHelpers) {

	$scope.summary = {};

	$scope.userTarget = UserTarget;
	$scope.routeParams = $routeParams;
	$scope.helpers = StatsHelpers;

	$scope.$on('$routeChangeSuccess', function () {
		if ($routeParams.userId) {
			$scope.load();
		}
	});

	$scope.$watch('helpers.dates', function () {
		$scope.load();
	});

	$scope.load = function () {
		if ($scope.loading)
			return false;

		$scope.loading = true;

		$http.get(apiUrl('stats/user/summary/' + $routeParams.userId), { params: { start_date: StatsHelpers.dates.startDate.format('X'), end_date: StatsHelpers.dates.endDate.format('X') } })
			.success(function (response) {
				$scope.summary = response;
				$scope.loading = false;
			})
			.error(ErrorsHandler);
	};

}]);
StatsModule.directive('feedbackList', [function () {
	return {
		restrict: 'A',
		scope: {
			reverse: '@',
			user: '@'
		},
		templateUrl: 'stats/feedback-list.html',
		controller: ['$scope', 'TaskFeedback', 'ErrorsHandler', '$paginator', function ($scope, TaskFeedback, ErrorsHandler, $paginator) {

			$paginator = angular.copy($paginator);
			$paginator.pages_to_show = 0;
			$paginator.edges = 0;
			$scope.paginator = $paginator;

			$paginator.setOnPageChange(function (page) {
				$scope.load(page);
			});

			$scope.$watch('user', function (value) {
				if (value) $scope.load();
			});

			$scope.load = function (page) {
				if (!page) page = 1;
				var reverse = $scope.reverse ? true : false;
				TaskFeedback.get({ completed: true, reverse: reverse, user: true, page: page, user_id: $scope.user }, function (response) {
					$scope.feedbacks = response.data;
					$scope.paginator.setFromResponse(response);
				}, ErrorsHandler);
				//                console.log('$scope.feedbacks -> ' $scope.feedbacks );
			};

			$scope.load();

		}]
	};
}])
StatsModule.directive('statsAverageFeedback', [function () {

	var template =
		'<dl class="dl-horizontal">' +
		'<dt>Repairs:</dt>' +
		'<dd data-tooltip="{[{ data.repair }]}"><uib-rating ng-model="data.repair" max="max" read-only="true"></uib-rating></dd>' +
		'<dt>Remote support:</dt>' +
		'<dd data-tooltip="{[{ data.support }]}"><uib-rating ng-model="data.support" max="max" read-only="true"></uib-rating></dd>' +
		'<dt>Onsite:</dt>' +
		'<dd data-tooltip="{[{ data.onsite }]}"><uib-rating ng-model="data.onsite" max="max" read-only="true"></uib-rating></dd>' +
		'</dl>';

	return {
		template: template,
		restrict: 'AE',
		scope: {
			'startDate': '=',
			'endDate': '='
		},
		controller: ['$scope', '$http', 'apiUrl', function ($scope, $http, apiUrl) {

			/**
			 * Object containing all the data
			 *
			 * @type Object
			 */
			$scope.data = {};

			/**
			 * Maxiumum amount of stars
			 *
			 * @type Number
			 */
			$scope.max = 5;

			/**
			 * Loads the data from the server
			 *
			 * @return null
			 */
			$scope.load = function () {
				var start_date = ($scope.startDate) ? $scope.startDate.format('X') : moment({ hour: 0, minute: 0, second: 0 }).format('X');
				var end_date = ($scope.endDate) ? $scope.endDate.format('X') : moment({ hour: 23, minute: 59, second: 59 }).format('X');

				$http.get(apiUrl('stats/overview/feedback-stats'), { params: { start_date: start_date, end_date: end_date } })
					.success(function (response) {
						$scope.data = response;
					});
			};

			/**
			 * Watch for when the view changes and reload the data
			 *
			 */
			$scope.$watchCollection('[startDate, endDate]', function (value) {
				$scope.load();
			});
		}]
	};
}])
StatsModule.directive('statsIncome', [function () {

	var template =
		'<dl class="dl-horizontal">' +
		'<dt>Repairs:</dt>' +
		'<dd ng-bind="data.repairs | currency:\'£\'"></dd>' +
		'<dt>Remote support:</dt>' +
		'<dd ng-bind="data.support | currency:\'£\'"></dd>' +
		'<dt>Onsite:</dt>' +
		'<dd ng-bind="data.onsite | currency:\'£\'"></dd>' +
		'<dt>Booking Fees:</dt>' +
		'<dd ng-bind="data.booking_fee | currency:\'£\'"></dd>' +
		'<dt>Contracts:</dt>' +
		'<dd ng-bind="data.contracts | currency:\'£\'"></dd>' +
		'</dl>' +
		'<hr>' +
		'<dl class="dl-horizontal">' +
		'<dt>Total:</dt>' +
		'<dd ng-bind="data.total | currency:\'£\'"></dd>' +
		'<dt>Wages:</dt>' +
		'<dd ng-bind="data.wages | currency:\'£\'"></dd>' +
		'<dt>Profit:</dt>' +
		'<dd ng-bind="data.profit | currency:\'£\'" ng-class="{\'text-danger\': data.profit < 0}"></dd>' +
		'</dl>';

	return {
		template: template,
		restrict: 'AE',
		scope: {
			'startDate': '=',
			'endDate': '='
		},
		controller: ['$scope', '$http', 'apiUrl', function ($scope, $http, apiUrl) {

			/**
			 * Object containing all the data
			 *
			 * @type Object
			 */
			$scope.data = {};

			/**
			 * Loads the data from the server
			 *
			 * @return null
			 */
			$scope.load = function () {
				var start_date = ($scope.startDate) ? $scope.startDate.format('X') : moment({ hour: 0, minute: 0, second: 0 }).format('X');
				var end_date = ($scope.endDate) ? $scope.endDate.format('X') : moment({ hour: 23, minute: 59, second: 59 }).format('X');

				$http.get(apiUrl('stats/overview/income'), { params: { start_date: start_date, end_date: end_date } })
					.success(function (response) {
						$scope.data = response;
					});
			};

			/**
			 * Watch for when the view changes and reload the data
			 *
			 */
			$scope.$watchCollection('[startDate, endDate]', function (value) {
				$scope.load();
			});
		}]
	};
}])
StatsModule.directive('statsPiechart', [function () {
	return {
		template: '<canvas class="chart chart-pie" chart-data="chart.data" chart-labels="chart.labels"></canvas>',
		restrict: 'AE',
		scope: {
			type: '@',
			dataType: '@',
			qaType: '@',
			startDate: '=',
			endDate: '='

		},
		controller: ['$scope', '$timeout', '$http', 'apiUrl', 'ErrorsHandler', function ($scope, $timeout, $http, apiUrl, ErrorsHandler) {

			/**
			 * Holds the piechart data
			 *
			 * @type Object
			 */
			$scope.chart = {
				labels: [],
				data: []
			};

			/**
			 * Sends an AJAX request to the server to load the data
			 *
			 * @return null
			 */
			$scope.load = function () {
				var start_date = ($scope.startDate) ? $scope.startDate.format('X') : null;
				var end_date = ($scope.endDate) ? $scope.endDate.format('X') : null;

				$http.get(apiUrl('stats/overview/pie-chart'), {
					params: {
						type: $scope.type,
						qa_type: $scope.qaType ? $scope.qaType : '',
						start_date: start_date,
						end_date: end_date

					}
				}).success(function (response) {
					var labels = [];
					var data = [];

					if ($scope.dataType == 'count') {
						_.each(response, function (item) {
							labels.push(item.user.name);
							data.push(item.cnt);
						});
					} else {
						_.each(response, function (item) {
							labels.push(item.user.name);
							data.push(item.labour);
						});
					}

					// Set the data for the chart
					$scope.chart.data = data;
					$scope.chart.labels = labels;
				}).error(ErrorsHandler);
			};

			/**
			 * Watch for when the view changes and reload the data
			 *
			 */
			$scope.$watchCollection('[startDate, endDate]', function (value) {
				$timeout(function () {
					$scope.load();
				}, 0);
			});

		}] // End of controller
	};
}])
StatsModule.directive('statsTasksList', [function () {

	var template =
		'<p class="lead">' +
		'All tasks associated with this user.' +
		'<span class="btn btn-default pull-right" data-ng-if="!requestOptions.showAll" data-ng-click="requestOptions.showAll = true">Show all</span>' +
		'<span class="btn btn-default pull-right" data-ng-if="requestOptions.showAll" data-ng-click="requestOptions.showAll = false">Display only results within selected dates</span>' +
		'</p>' +
		'<div>' +
		'<div ui-grid="grid" style="min-height: 650px;"></div>' +
		'<div paginator="paginator"></div>' +
		'</div>';

	return {
		template: template,
		restrict: 'AE',
		scope: {
			'userId': '=',
			'startDate': '=',
			'endDate': '='
		},
		controller: ['$scope', '$http', 'apiUrl', 'Tasks', 'ErrorsHandler', '$paginator', function ($scope, $http, apiUrl, Tasks, ErrorsHandler, $paginator) {

			var colorTemplate =
				'<div class="ui-grid-cell-contents text-center">' +
				'<span ng-show="row.entity.completed == \'1\' && row.entity.paid == \'1\'" class="badge badge-success" tooltip="Paid">&nbsp;</span>' +
				'<span ng-show="row.entity.completed == \'0\'" class="badge badge-warning" tooltip="In progress">&nbsp;</span>' +
				'<span ng-show="row.entity.completed == \'1\' && row.entity.paid == \'0\' && row.entity.invoiced == \'1\'" class="badge badge-important" tooltip="Awaiting payment">&nbsp;</span>' +
				'<span ng-show="row.entity.completed == \'1\' && row.entity.paid == \'0\' && row.entity.invoiced == \'0\'" class="badge" tooltip="Needs invoicing">&nbsp;</span>' +
				'</div>';

			/**
			 * Create a new instance of the paginator
			 *
			 * @type $paginator
			 */
			$paginator = angular.copy($paginator);
			$scope.paginator = $paginator;

			/**
			 * Set a function to execute on page change
			 *
			 * @param  int page
			 * @return null
			 */
			$paginator.setOnPageChange(function (page) {
				$scope.requestOptions.params.page = page;
				$scope.load();
			});

			/**
			 * An object containing all the request options
			 *
			 * @type Object
			 */
			$scope.requestOptions = {
				showAll: false,
				params: {
					page: 1,
					summary: true,
					client: true,
					parts_total: true
				}
			};

			/**
			 * Define the grid object
			 *
			 * @type Object
			 */
			$scope.grid = {};
			// $scope.grid.options = {
			// 	enableSorting: true
			// };
			$scope.grid.enableFiltering = false;
			$scope.grid.useExternalPaging = true;
			$scope.grid.useExternalSorting = true;
			$scope.grid.useExternalFiltering = true;
			$scope.grid.pagingPageSize = 20;
			$scope.grid.enableHorizontalScrollbar = false;
			$scope.grid.columnDefs = [
				{ name: 'color', 'displayName': '', width: 50, enableSorting: false, enableHiding: false, enableColumnMenu: false, cellTemplate: colorTemplate },
				{ name: 'id', enableColumnMenu: false, cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="/tasks/{{ row.entity | taskUrl }}">{{ COL_FIELD }}</a></div>', width: 75, type: 'number' },
				{ name: 'type', width: 75 },
				{ name: 'title', enableColumnMenu: false, enableSorting: false },
				{
					name: 'customer',
					enableHiding: false,
					cellTemplate: '<div class="ui-grid-cell-contents">{{ row.entity.client.name }}</div>',
					menuItems: [
						{
							title: 'Business',
							icon: 'fa fa-fw fa-building',
							action: function () {
								$scope.requestOptions.params.client_type = 'client';
							}
						},
						{
							title: 'Regular Customers',
							icon: 'fa fa-fw fa-user',
							action: function () {
								$scope.requestOptions.params.client_type = 'client';
							}
						},
						{
							title: 'All Customers',
							icon: 'fa fa-fw fa-cross',
							action: function () {
								delete $scope.requestOptions.params.client_type;
							}
						}
					]
				},
				{ name: 'labour', enableHiding: false, cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD | currency:"£" }}</div>', type: 'number' },
				{ name: 'points', enableHiding: false, cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD }}</div>', type: 'number' },
				{ name: 'parts_total', enableHiding: false, cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD | currency:"£" }}</div>', type: 'number' },
				{ name: 'status', enableHiding: false, cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ row.entity.status.name }}</div>' },
				{ name: 'invoiced', width: 80, cellTemplate: '<div class="ui-grid-cell-contents text-center"><i class="fa" ng-class="{\'fa-check\': row.entity.invoiced == \'1\'}"></i></div>' },
				{ name: 'paid', width: 60, cellTemplate: '<div class="ui-grid-cell-contents text-center"><i class="fa" ng-class="{\'fa-check\': row.entity.paid == \'1\'}"></i></div>' },
				{ name: 'completed_at', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD | fromNow }}</div>' },
				{ name: 'created_at', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD | fromNow }}</div>' }
			];
			$scope.grid.data = [];
			$scope.grid.onRegisterApi = function (gridApi) {
				$scope.gridApi = gridApi;
				$scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {

					if (sortColumns.length > 0) {
						$scope.requestOptions.params.orderBy = sortColumns[0].field;
						$scope.requestOptions.params.orderType = sortColumns[0].sort.direction;
					}
					else {
						$scope.requestOptions.params.orderBy = null;
						$scope.requestOptions.params.orderType = null;
					}

					$scope.load();
				});
				$scope.gridApi.core.on.filterChanged($scope, function () {
					var grid = this.grid;
				});
			};

			/**
			 * Sends an ajax call to the server to load the users data.
			 *
			 * @return null
			 */
			$scope.load = function () {
				/*
				$http.get(apiUrl('stats/user/repairs/' + $scope.userId), $scope.requestOptions).success(function(response) {
					$scope.grid.data = response.data;
					$paginator.setFromResponse(response);
				}).error(ErrorsHandler);
				*/
				Tasks.get($scope.requestOptions.params, function (response) {
					$scope.grid.data = response.data;
					$paginator.setFromResponse(response);
				}, ErrorsHandler);
			};

			/**
			 * Watch for changes to the scope attributes and reload the data
			 *
			 * @return null
			 */
			$scope.$watchCollection('[userId, startDate, endDate, requestOptions.showAll]', function () {
				$scope.requestOptions.params.start_date = ($scope.startDate && !$scope.requestOptions.showAll) ? $scope.startDate.format('X') : null;
				$scope.requestOptions.params.end_date = ($scope.endDate && !$scope.requestOptions.showAll) ? $scope.endDate.format('X') : null;
				$scope.requestOptions.params.assigned_to = $scope.userId ? $scope.userId : null;

				$scope.load();
			});

		}] // End of controller
	};
}])

StatsModule.directive('statsUsersList', [function () {
	return {
		template: '<div ui-grid="grid" style="height: 500px;"></div>',
		restrict: 'A',
		scope: {
			'startDate': '=',
			'endDate': '='
		},
		controller: ['$scope', '$http', 'apiUrl', 'ErrorsHandler', '$filter', '$timeout', function ($scope, $http, apiUrl, ErrorsHandler, $filter, $timeout) {

			/**
			 * Define the grid object
			 *
			 * @type Object
			 */
			$scope.grid = {};
			$scope.grid.options = {
				enableSorting: true
			};
			$scope.grid.enableFiltering = false;
			$scope.grid.columnDefs = [
				{ name: 'name', cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#/stats/user/{{ row.entity.id }}">{{ COL_FIELD }}</a></div>' },
				// { name: 'feedback', cellTemplate: '<div class="ui-grid-cell-contents text-center" tooltip="{{ COL_FIELD }}"><rating value="COL_FIELD" max="5" readonly="true"></rating></div>' },
				{ name: 'repairs', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD }}</div>', type: 'number' },
				{ name: 'remoteSupport', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD }}</div>', type: 'number' },
				{ name: 'onsite', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD }}</div>', type: 'number' },
				{ name: 'labour', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD | currency:"£" }}</div>', type: 'number' },
				{ name: 'parts', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD | currency:"£" }}</div>', type: 'number' },
				{ name: 'period_points', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD }}</div>', type: 'number' }
			];
			$scope.grid.data = [];

			/**
			 * Sends an ajax call to the server to load the users data.
			 *
			 * @return null
			 */
			$scope.load = function () {
				var start_date = ($scope.startDate) ? $scope.startDate.format('X') : moment({ hour: 0, minute: 0, second: 0 }).format('X');
				var end_date = ($scope.endDate) ? $scope.endDate.format('X') : moment({ hour: 23, minute: 59, second: 59 }).format('X');

				$http.get(apiUrl('stats/overview/users'), { params: { start_date: start_date, end_date: end_date } })
					.success(function (response) {
						$scope.grid.data = response;
					}).error(ErrorsHandler);
			};

			/**
			 * Watch for when the view changes and reload the data
			 *
			 */
			$scope.$watchCollection('[startDate, endDate]', function (value) {
				$timeout(function () {
					$scope.load();
				}, 100);
			});

		}] // End of controller
	};
}])

StatsModule.directive('statsUsersRepairsList', [function () {
	return {
		template: '<div ui-grid="grid" style="height: 500px;"></div>',
		restrict: 'A',
		scope: {
			'startDate': '=',
			'endDate': '='
		},
		controller: ['$scope', '$http', 'apiUrl', 'ErrorsHandler', '$filter', '$timeout', function ($scope, $http, apiUrl, ErrorsHandler, $filter, $timeout) {

			/**
			 * Define the grid object
			 *
			 * @type Object
			 */
			$scope.grid = {};
			$scope.grid.enableFiltering = false;
			$scope.grid.enableHorizontalScrollbar = false;
			$scope.grid.columnDefs = [
				{ name: 'name', cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#/stats/user/{{ row.entity.id }}">{{ COL_FIELD }}</a></div>' },
				{ name: 'completed', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD }}</div>' },
				{ name: 'open', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD }}</div>' },
				{ name: 'parts', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD | currency:"£" }}</div>' },
				{ name: 'labour', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD | currency:"£" }}</div>' },
				{ name: 'points', cellTemplate: '<div class="ui-grid-cell-contents text-center">{{ COL_FIELD }}</div>' }
			];
			$scope.grid.data = [];

			/**
			 * Sends an ajax call to the server to load the users data.
			 *
			 * @return null
			 */
			$scope.load = function () {
				var start_date = ($scope.startDate) ? $scope.startDate.format('X') : moment({ hour: 0, minute: 0, second: 0 }).format('X');
				var end_date = ($scope.endDate) ? $scope.endDate.format('X') : moment({ hour: 23, minute: 59, second: 59 }).format('X');

				$http.get(apiUrl('stats/repairs/users'), { params: { start_date: start_date, end_date: end_date } })
					.success(function (response) {
						$scope.grid.data = response;
					}).error(ErrorsHandler);
			};

			/**
			 * Watch for when the view changes and reload the data
			 *
			 */
			$scope.$watchCollection('[startDate, endDate]', function (value) {
				$timeout(function () {
					$scope.load();
				}, 100);
			});

		}] // End of controller
	};
}])
StatsModule.directive('labourPointsGraph', [function () {

	var template =
		'<div class="widget widget-classic">' +
		'<div class="widget-content form-inline">' +

		'<p class="lead">' +
		'<select class="form-control" ng-model="filter.view" ng-options="o.id as o.name for o in views"></select>' +
		'<span class="pull-right">Income over the selected period of time</span>' +
		'</p>' +
		'<canvas class="chart chart-line" chart-data="linechart.data" chart-labels="linechart.labels" chart-series="linechart.series"></canvas>' +

		'</div>' +
		'</div>';


	return {
		template: template,
		replace: true,
		restrict: 'AE',
		scope: {
			'userId': '=',
			'startDate': '=',
			'endDate': '=',
			'url': '@'
		},
		controller: ['$scope', 'apiUrl', '$http', 'ErrorsHandler', function ($scope, apiUrl, $http, ErrorsHandler) {

			/**
			 * Store the filters that we pass to the server request
			 *
			 * @type Object
			 */
			$scope.filter = {
				view: 'weekly',
			};

			/**
			 * A list containing all the possible views
			 *
			 * @type Array
			 */
			$scope.views = [
				{ id: 'daily', name: 'Daily' },
				{ id: 'weekly', name: 'Weekly' },
				{ id: 'monthly', name: 'Monthly' },
				{ id: 'yearly', name: 'Yearly' }
			];

			/**
			 * Definition of the line chart
			 *
			 * @type Object
			 */
			$scope.linechart = {
				data: [],
				series: ['Labour', 'Points', 'Wages'],
				labels: []
			};

			/**
			 * Load data from the server
			 *
			 * @return null
			 */
			$scope.load = function () {
				var url;
				var start_date = ($scope.startDate) ? $scope.startDate.format('X') : moment({ hour: 0, minute: 0, second: 0 }).format('X');
				var end_date = ($scope.endDate) ? $scope.endDate.format('X') : moment({ hour: 23, minute: 59, second: 59 }).format('X');

				if ($scope.url) {
					url = $scope.url;
				}
				else {
					url = ($scope.userId) ? apiUrl('stats/user/graph/' + $scope.userId) : apiUrl('stats/overview/graph');
				}

				$http.get(url, { params: { start_date: start_date, end_date: end_date, view: $scope.filter.view } })
					.success(function (response) {
						$scope.linechart.data = [[], [], []];
						$scope.linechart.labels = [];

						_.each(response.labour, function (item) {
							$scope.linechart.labels.push(item.date);
						});
						_.each(response.points, function (item) {
							$scope.linechart.labels.push(item.date);
						});
						_.each(response.wages, function (item) {
							$scope.linechart.labels.push(item.date);
						});

						// Sort the data array
						$scope.linechart.labels = _.sortBy($scope.linechart.labels, function (item) {
							return item;
						});

						// Insert data
						_.each($scope.linechart.labels, function (date) {
							var labour = _.find(response.labour, function (item) {
								return item.date == date;
							});
							$scope.linechart.data[0].push(labour ? labour.cnt : null);

							var points = _.find(response.points, function (item) {
								return item.date == date;
							});
							$scope.linechart.data[1].push(points ? points.cnt : null);

							var wages = _.find(response.wages, function (item) {
								return item.date == date;
							});
							$scope.linechart.data[2].push(wages ? wages.cnt : null);
						});
					})
					.error(ErrorsHandler);
			};

			/**
			 * Watch for when the view changes and reload the data
			 *
			 */
			$scope.$watchCollection('[filter.view, startDate, endDate]', function (value) {
				$scope.load();
			});

		}]
	};
}])
/**
 * Stock Module
 *
 */
