(function() {
	'use strict';

	window.app.controller('TransactionController', TransactionController);

	TransactionController.$inject = ['$scope', '$uibModal', 'transactionSvc', 'inventorySvc', 'uiGridConstants'];
	function TransactionController($scope, $uibModal, transactionSvc, inventorySvc, uiGridConstants) {
		var vm = this;

		var paginationOptions = {
			pageNumber: 1,
			pageSize: 20,
			pageSizes: [20,50,100],
			sort: null
		};

		vm.gridOptions = {
			enablePaginationControls: true,
			paginationPageSize: paginationOptions.pageSize,
			paginationPageSizes: paginationOptions.pageSizes,
			useExternalPagination: true,
			enableSorting: false,
			columnDefs: [
				{
					field: 'name',
					cellTooltip: function(row) {
						return row.entity.name + "\r" + row.entity.unitsPerCase + " / " + row.entity.containerType;
					},
					cellTemplate: '<div class="ui-grid-cell-contents" ' +
						'title="{{row.entity.name}}' +
						'\r{{row.entity.unitsPerCase}} / {{row.entity.containerType}}' +
						'\rExp Date: {{row.entity.expirationDate | date:\'shortDate\'}}' +
						'\rAdd Date: {{row.entity.addedDate | date:\'shortDate\'}}">' +
						'<a href="" ng-click="grid.appScope.editInventory(row.entity.inventoryId)"><i class="fa fa-edit"></i></a> ' +
						'{{row.entity.name}}</div>'
				},
				{ field: 'transactionType', name: 'Type', width: "10%" },
				{ field: 'memo', cellTooltip: true },
				{ field: 'transactionDate', name: 'Transaction Date', cellFilter: "date:'shortDate'", width: "15%" },
				{ field: 'previousQuantity', name: 'Prev Qty', width: "10%", enableSorting: false },
				{ field: 'addedQuantity', name: 'Add Qty', width: "10%", enableSorting: false, cellFilter: "hideZero" },
				{ field: 'removedQuantity', name: 'Remove Qty', width: "10%", enableSorting: false, cellFilter: "hideZero" },
				{ field: 'currentQuantity', name: 'Current Qty', width: "15%", enableSorting: false }
			],
			onRegisterApi: function(gridApi) {
				vm.gridApi = gridApi;
				vm.gridApi.pagination
					.on.paginationChanged($scope, function(pageNumber, pageSize) {
						paginationOptions.pageNumber = pageNumber;
						paginationOptions.pageSize = pageSize;
						updateData();
					});
			}
		};

		function updateData() {
			transactionSvc
				.filterByPage(paginationOptions.pageNumber, paginationOptions.pageSize)
				.success(function (data) {
					vm.gridOptions.data = data.transactions;
					vm.gridOptions.totalItems = data.totalItems;
				});
		}

		updateData();

		$scope.editInventory = function (inventoryId) {
			inventorySvc.find(inventoryId)
				.success(function(inventory) {
					$uibModal.open({
							template: '<edit-inventory inventory="inventory" />',
							scope: angular.extend($scope.$new(true), { inventory: inventory })
						})
						.closed.then(function() {
							updateData();
						});
				});
		}
	}
})();