'use strict';

var q = require("q");
var logger = require('../../utils/Logger').loggers.get('db');
var UpdateService = require('./UpdateService');

var setDeleteFlag = function(id, userId, options, flag) {
    logger.info("Setting deleted flag on " + id);

    // send through the updates necessary to delete the document rather than have a separate delete function. The delete permissions
    // will need to be checked in the update function. This allows us to block updates that manually set the deleted flag to true
    // when the user doesn't have delete access
    var updates = {
        systemHeader: {
            deleted: flag
        }
    };

    if (options.templateId) {
        updates.systemHeader.createdWith = options.templateId;
    }

    if (options.previousVersionId) {
        updates.systemHeader.previousVersionId = options.previousVersionId;
    }

    return UpdateService.update(id, updates, userId, options);
};

const destroy = (id, userId, options) => {
    return setDeleteFlag(id, userId, options, true);
};
const undestroy = (id, userId, options) => {
    return setDeleteFlag(id, userId, options, false);
};

module.exports = {
    destroy: destroy,
    undestroy: undestroy

};
