"use strict";
var Handlebars = require('handlebars/dist/handlebars');
var SharedConstants = require('../../shared/constants/SharedConstants');
var _ = require('lodash/lang');

const lodashCloneDeep = require('lodash.clonedeep');

module.exports = {
    writeSystemHeaderValue: function(doc, handlebarsSource) {
        var result;

        if (handlebarsSource && doc) {
            var hbTemplate;
            hbTemplate = Handlebars.compile(handlebarsSource);
            result = hbTemplate(doc);
        }

        return result;
    },

    writeSystemHeaderSummary: function(newRecord, template, oldRecord, updates) {
        if(!template || !newRecord) {
          return;
        }
        const nameSource = template.summaryNameRule;
        const descriptionSource = template.summaryDescriptionRule;
        if (nameSource){
            // TODO: study removal. May affect 14106
            //  the ff condition may no longer reach as updates now uses the jsonpatch update formatting:
            // eslint-disable-next-line max-len
            // {"updates":[{"op":"remove","path":"/analyserMedium"},{"op":"replace","path":"/systemHeader/createdDate","value":1677714723207}],"documentId":"44e6a730-9163-11ed-b170-bb8c64dbe8c0"}
            if (updates && updates.systemHeader && updates.systemHeader.summaryName) {
                newRecord.systemHeader.summaryName = updates.systemHeader.summaryName;
            } else {
                newRecord.systemHeader.summaryName = Handlebars.compile(nameSource)(newRecord);
            }
        }
        if (descriptionSource){
            if (updates && updates.systemHeader && updates.systemHeader.summaryDescription) {
                newRecord.systemHeader.summaryDescription = updates.systemHeader.summaryDescription;
            } else {
                newRecord.systemHeader.summaryDescription = Handlebars.compile(descriptionSource)(newRecord);
            }
        }
    },

    writeSystemHeaderCreated: function (newRecord, operationType, user, now) {
        // Write on insert and update.
        // The created fields represent when and who created this version of the document.

        if (operationType === SharedConstants.INSERT_OPERATION_TYPE
                || operationType === SharedConstants.UPDATE_OPERATION_TYPE) {

            if (!newRecord.systemHeader.createdDate) {
                newRecord.systemHeader.createdDate = (now ? now : new Date());
            }
            if (user) {
                newRecord.systemHeader.createdBy = user.documentId;
            }
        }

        if (operationType === SharedConstants.INSERT_OPERATION_TYPE){
          if (!newRecord.systemHeader.documentCreatedDate) {
            newRecord.systemHeader.documentCreatedDate = (now ? now : new Date());
          }
          if (user && !newRecord.systemHeader.documentCreatedBy) {
            newRecord.systemHeader.documentCreatedBy = user.documentId;
          }
        }
    }

};
