/**
 * MarketingCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('MarketingCtrl', ['$scope', 'Marketing', 'ErrorsHandler', 'Messenger', '$window', function ($scope, Marketing, ErrorsHandler, Messenger, $window) {

	/**
	 * Represents the total number of customer
	 * that can be reached with the current filters
	 *
	 * @type integer
	 */
	$scope.total_reach = 0;

	/**
	 * Custom filter that are applied
	 *
	 * @type Object
	 */
	$scope.filters = {};

	// Watch to see when any of the filters changes
	// and we will reload the stats
	$scope.$watch('filters', function (value) {
		$scope.loadReach();
	}, true);

	$scope.$watch('inactive_since', function (value) {
		$scope.filters.inactive_since = (value) ? moment(value).format("YYYY-MM-DD 00:00:00") : null;
	});

	/**
	 * Loads the potential number of customers that can be reached.
	 *
	 * @return null
	 */
	$scope.loadReach = function () {
		Marketing.reach($scope.filters, function (response) {
			$scope.total_reach = response.total;
		}, ErrorsHandler);
	};

	$scope.preview = function () {
		Marketing.preview($scope.email, function (response) {
			Messenger(response.message);
			alert(response.message);
		}, ErrorsHandler);
	};

	$scope.export = function () {
		$scope.exporting = true;

		Marketing.export($scope.filters, function (response) {
			if (response.file) $window.location = response.file;
			$scope.exporting = false;
		}, function (a, b) {
			$scope.exporting = false;
			ErrorsHandler(a, b);
		});
	};

}]);
