angular.module('bookmarks.bookmarks-service', [
]).service('bookmarksService', function($q, mongolabFactory) {
    'use strict';

    var connection = mongolabFactory('bookmarks');
    var self = this;

    this.bookmarks = [];

    this.init = function() {
        var deferred = $q.defer();

        connection.query(function (bookmarks) {
            self.bookmarks = bookmarks;
            deferred.resolve(self.bookmarks);
        });

        return deferred.promise;
    };

    this.edit = function(bookmark) {
        var deferred = $q.defer();
        connection.update({id: bookmark._id.$oid}, angular.toJson(bookmark)).$promise.then(function (bookmark) {
            delete bookmark.$promise;
            delete bookmark.$resolved;

            var found = _.find(self.bookmarks, ['_id', bookmark._id]);
            _.assign(found, bookmark);

            deferred.resolve(self.bookmarks);
        });

        return deferred.promise;
    };

    this.save = function(bookmark) {
        var deferred = $q.defer();

        connection.save(angular.toJson(bookmark)).$promise.then(function (bookmark) {
            delete bookmark.$promise;
            delete bookmark.$resolved;
            
            self.bookmarks.push(bookmark);
            deferred.resolve(self.bookmarks);
        });

        return deferred.promise;
    };

    this.delete = function(bookmark) {
        var deferred = $q.defer();

        connection.delete({id: bookmark._id.$oid}).$promise.then(function (bookmark) {
            _.remove(self.bookmarks, function(b) {
                return b._id.$oid === bookmark._id.$oid;
            });

            deferred.resolve(self.bookmarks);
        });

        return deferred.promise;
    };
});
