poconsole.factory('devices', function($q, $http, $log){
    var getAllDevices = function(){
        var deferred = $q.defer();
        $http.get('/device').success(function(data) {
        	deferred.resolve({
    			devices:data
    		});
        });
        return deferred.promise;
    };

    var getDevice = function(id){
        var deferred = $q.defer();
        $http.get('/device/'+ id).success(function(data) {
        	deferred.resolve({
    			devices:data
    		});
        });
        return deferred.promise;
    };

    var addDevice = function(d){
        $log.info(d);
        var deferred = $q.defer();
        $http.post('/device/create', {
            address: d.address,
            device_type: d.device_type.id
        }).success(function(data){
            deferred.resolve({
                data:data
            });
        });
        return deferred.promise;
    };

    var updateDevice = function(d){
        var deferred = $q.defer();
        $http.post('/device/update/' + d.id, {
            address: d.address,
            device_type: d.device_type.id
        }).success(function(data){
            deferred.resolve({
                data:data
            });
        });
        return deferred.promise;
    };

    var deleteDevice = function(id){
        var deferred = $q.defer();
        var url = '/device/' + id;
        $http.delete(url).success(function(data) {
            deferred.resolve({
                data:data
            });
        });
        return deferred.promise;
    };

    var getDeviceTypes = function(){
        var deferred = $q.defer();
        $http.get('/device_type').success(function(data) {
        	deferred.resolve({
    			device_types:data
    		});
        });
        return deferred.promise;
    };


    return {
        getAllDevices : getAllDevices,
        getDevice: getDevice,
        addDevice: addDevice,
        deleteDevice: deleteDevice,
        updateDevice: updateDevice,
        getDeviceTypes: getDeviceTypes

    };
});
