/**
 * LicensesModalCtrl Controller
 * Extracted from clients module
 */

ClientsModule.controller('LicensesModalCtrl', ['$scope', 'Customer', 'License', '$q', 'ErrorsHandler', '$uibModalInstance', function ($scope, Customer, License, $q, ErrorsHandler, $uibModalInstance) {

	$scope.new = {};

	$scope.load = function () {
		License.get({ client_id: Customer.id, client_type: Customer.type }, function (response) {
			$scope.licenses = response.data;
		}, ErrorsHandler);
	};

	$scope.load();

	$scope.add = function () {
		$scope.new.client_type = Customer.type;
		$scope.new.client_id = Customer.id;

		License.save($scope.new, function (response) {
			$scope.licenses.push(response);
		}, ErrorsHandler);
	};

	$scope.update = function (license, field, value) {
		var data = { id: license.id },
			deferred = $q.defer();
		data[field] = value;

		License.update(data, function (response) {
			deferred.resolve();
			angular.extend(license, response || {});
		}, function (a, b) {
			ErrorsHandler(a, b);
			deferred.resolve('Something went wrong');
		});

		return deferred.promise;
	};

	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

}]);
