'use strict';

// fields to remove from systemHeader. Each field in the array will be removed
var fieldsToExclude = [
    "serverCreatedDate",
    "serverUpdatedDate",
    "previousVersionId"
];

/**
 * remove any values from systemHeader that shouldn't be updated, as specified in 
 * Mantis 10975: Do not overwrite values in systemHeader that aren't included in update
 * @param {*} document 
 */
function filterSystemHeader(document) {
    if (document.systemHeader) {
        for (var i = 0; i < fieldsToExclude.length; i++) {
            delete document.systemHeader[fieldsToExclude[i]];
        }
    }
}


/**
 * When update or jsonPatchUpdate functions are called, only those values in
 * the update that are passed in as part of the systemHeader should be updated. Other values in
 * the systemHeader should not be removed or changed
 * Mantis 10975: Do not overwrite values in systemHeader that aren't included in update
 */
function applyUpdatesToSystemHeader(origDoc, newDoc){
    if (newDoc.systemHeader){

        filterSystemHeader(origDoc);
        filterSystemHeader(newDoc);

        var updateKeys = Object.keys(newDoc.systemHeader);

        if (!origDoc.systemHeader){
            origDoc.systemHeader = {};
        }

        for (var i = 0; i < updateKeys.length; i++) {
            var fieldName = updateKeys[i];
            var value = newDoc.systemHeader[fieldName];
            if (fieldName !== "currentVersion"){
                origDoc.systemHeader[fieldName] = value;
            }
        }
    }

}

module.exports = {
    filterSystemHeader: filterSystemHeader,
    applyUpdatesToSystemHeader: applyUpdatesToSystemHeader
};