/**
 * KashflowSyncCtrl Controller
 * Extracted from invoices module
 */

Invoices.controller('KashflowSyncCtrl', ['$scope', '$http', 'apiUrl', 'ErrorsHandler', '$uibModal', function ($scope, $http, apiUrl, ErrorsHandler, $uibModal) {

	$scope.loading = false;

	$scope.load = function () {
		// Exit if loading already in progress
		if ($scope.loading) return false;

		$scope.loading = true;
		$scope.sync_failed = null;
		$scope.data = null;

		$http.get(apiUrl('kashflow/changes'))
			.success(function (response) {
				$scope.loading = false;
				$scope.data = response;
			})
			.error(function (a, b) {
				$scope.loading = false;
				ErrorsHandler(a, b);
			});
	};

	$scope.check = function (invoices) {
		_.each(invoices, function (el) {
			el.checked = !el.checked;
		});
	};

	$scope.sync = function () {
		if ($scope.syncing) return false;
		$scope.syncing = true;

		$http.post(apiUrl('kashflow/sync-changes'), $scope.data)
			.success(function (response) {
				$scope.syncing = false;
				$scope.sync_results = response;
				$scope.sync_failed = {
					changed: _.countBy(response.changes, function (el) { return el.success ? 'success' : 'failed'; }),
					missingKashflow: _.countBy(response.missingKashflow, function (el) { return el.success ? 'success' : 'failed'; }),
					missingLocal: _.countBy(response.missingLocal, function (el) { return el.success ? 'success' : 'failed'; })
				};
				$scope.applySyncResults();
			})
			.error(function (a, b) {
				$scope.syncing = false;
				ErrorsHandler(a, b);
			});
	};

	$scope.applySyncResults = function () {
		_.each($scope.sync_results, function (result, index) {
			_.each(result, function (el) {
				var item = _.find($scope.data[index], function (i) {
					if (index == 'changed')
						return i.local.invoice_number == el.invoice_number;
					else if (index == 'missingLocal')
						return i.InvoiceNumber == el.invoice_number;
					else if (index == 'missingKashflow')
						return i.invoice_number == el.invoice_number;
				});
				if (item) {
					item.checked = false;
					item.sync_result = {
						success: el.success,
						message: el.error
					};
				}
			});
		});
	};

	$scope.showComparison = function (data) {
		var modalInstance = $uibModal.open({
			templateUrl: 'kashflow/modals/sync-comparison.html',
			controller: 'InvoicesSyncComparisonCtrl',
			windowClass: 'modal-fixed',
			resolve: {
				Data: function () {
					return data;
				}
			}
		});
	};

}]);
