(function() {
	"use strict";

	window.app.controller("TransactionController",
	[
		"$scope", "$uibModal", "transactionSvc", "inventorySvc", "uiGridConstants",
		function($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: "inventoryId",
						cellTooltip: function(row) {
							return row.entity.name;
						},
						cellTemplate: '<div class="ui-grid-cell-contents" ' +
							'title="{{row.entity.inventoryId}}">' +
							'<a href="" ng-click="grid.appScope.editInventory(row.entity.inventoryId)"><i class="fa fa-edit"></i></a> ' +
							"{{row.entity.inventoryId}}</div>",
						width: "10%"
					},
					{
						field: "programName",
						cellTemplate: '<div class="ui-grid-cell-contents" ' +
							'title="{{row.entity.program}}">' +
							"{{row.entity.programName}}" +
							"{{(row.entity.programSubtype ? ' ' + row.entity.programSubtype : '')}}" +
							"</div>",
						width: "15%"
					},
					{ field: "description", cellTooltip: true, width: "15%" },
					{ field: "transactionDate", name: "Transaction Date", cellFilter: "date:'shortDate'", width: "10%" },
					{ field: "transactionType", cellToolTip: true, width: "10%" },
					{ field: "memo", cellTooltip: true, width: "15%" }
				],
				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.load(inventoryId)
					.success(function () {
						var inventory = inventorySvc.get(inventoryId);
						$uibModal.open({
								template: '<edit-inventory inventory="inventory" />',
								scope: angular.extend($scope.$new(true), { inventory: inventory })
							})
							.closed.then(function() {
								updateData();
							});
					});
			};
		}
	]);
})();