"use strict";

var q = require("q");

var cleanRelatedDocs = function(docs) {

    //remove _uiSelectChoiceLocked field
    for (var i = 0; i < docs.length; i++) {
        if("_uiSelectChoiceLocked" in docs[i]) {
            delete docs[i]["_uiSelectChoiceLocked"];
        }
    };
};

module.exports.preProcess = function(field, document, userId) {
    var deferred = q.defer();

    if(document[field.name]) {
        if(field.singleSelection === true  && document[field.name].length > 1) {
                var errMsg = "Related document definition has singleSelection set to true, "
                + "but more than one value is being saved";
                deferred.reject(errMsg);
            } else {
                cleanRelatedDocs(document[field.name]);
                deferred.resolve(document);
            }
    } else {
        deferred.resolve(document);
    }

	return deferred.promise;
};