'use strict';

app.factory('Learning', function ($http, $q, Systems) {


	function start(id) {
		var d = $q.defer();
		var canceller = $q.defer(); 

		var cancel = function(reason){
			canceller.resolve(reason);
		};

		var jsonData = JSON.stringify({ systemId: id});
		
		var promise = $http({ method: 'POST', url: '/api/cloud/learn_start', data: jsonData, timeout: canceller.promise });
		
		promise.success(function(response) {
			console.log(response);
			if (response.result) {
				d.resolve(response.result);
			} else {
				d.reject(response.error);
			}
		}).error(function(error) {
			console.log(error);
			d.reject(error);
		});

		return { 
			promise: d.promise,
			cancel: cancel
		};
	}

	

	function attempt(id) {
		var d = $q.defer();
		var canceller = $q.defer(); 

		var jsonData = JSON.stringify({ systemId: id});

		var cancel = function(reason){
			canceller.resolve(reason);
		};

		var promise = $http({ method: 'POST', url: '/api/cloud/learn_data', data: jsonData, timeout: canceller.promise });
		
		promise.success(function(response) {
			if (response.result) {
				d.resolve(response.data);
			} else {
				d.reject(response.error);
			}
		}).error(function(error) {
			d.reject(error);
		});

		return { 
			promise: d.promise,
			cancel: cancel
		};
	}

	return {
		start: start,
		attempt: attempt
	};

});