'use strict';

var q = require("q");
var utilSystemHeader = require('../../../shared/utils/UtilSystemHeader');
var UtilDocumentId = require('../../../shared/utils/UtilDocumentId');
var SharedConstants = require('../../../shared/constants/SharedConstants');
var UtilType = require('../../../shared/utils/UtilType');
var logger = require('../../utils/Logger').loggers.get('db');

function applySystemType(newRecord, template) {
    if (!newRecord.systemHeader) {
        newRecord.systemHeader = {};
    }

    // perform override if it exists
    if (template && template.systemTypeOverride) {
        newRecord.systemHeader.systemType = template.systemTypeOverride;
    }

    // default value if not set
    if (!newRecord.systemHeader.systemType) {
        newRecord.systemHeader.systemType = SharedConstants.SYSTEM_TYPE_DOCUMENT;
    }
}

/*
 writeSystemHeader - write the system header
 parameters:
 query - a mongodb query to run. This can be any mongodb query
 operationType - the type of the operation - insert, update, or delete
 */
function writeSystemHeader(newRecord, operationType, user, template, oldRecord, updates, now) {
    if (!user) {
        logger.warn("No user for insert");
    }

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

    now = (now == null) ? new Date() : now;

    utilSystemHeader.writeSystemHeaderCreated(newRecord, operationType, user, now);

    newRecord.systemHeader.serverUpdatedDate = now;
    newRecord.systemHeader.serverCreatedDate = now;

    //Version documents might be inserted from offline save where their versionId has already been assigned.
    //Documents might be updated from offline save, where its versionId is retained (original doc is cloned with a new versionId)
    var version = newRecord.systemHeader.versionId;
    newRecord.systemHeader.versionId = (version == null ? UtilDocumentId.generateId() : version);

    if (operationType === SharedConstants.INSERT_OPERATION_TYPE) {

        if (template && template.excludeGeneralSearch === true) {
            newRecord.systemHeader.excludeGeneralSearch = true;
        }

        //Version documents might be inserted from offline save where their currentVersion = false.
       var isCurrentVersion = newRecord.systemHeader.currentVersion;
       newRecord.systemHeader.currentVersion = isCurrentVersion != null ? isCurrentVersion : true;
        //Inserted document should be current version
        // newRecord.systemHeader.currentVersion = true;

    } else if (operationType === SharedConstants.UPDATE_OPERATION_TYPE) {

        if (oldRecord && oldRecord.systemHeader && oldRecord.systemHeader.versionId) {
            var previousVersionId = oldRecord.systemHeader.versionId;

            //only set new previousVersionId when its unchanged or undefined
            if (!newRecord.systemHeader.previousVersionId || newRecord.systemHeader.previousVersionId === previousVersionId) {
                newRecord.systemHeader.previousVersionId = previousVersionId;
            }
        }
    }

    if (template) {
        try {
            logger.debug("Writing system header values from template: " + template.documentId);

            utilSystemHeader.writeSystemHeaderSummary(newRecord, template, oldRecord, updates);
        } catch (ex) {
            logger.error(ex);
        }
    } else {
        logger.warn("No template found when writing system header");
    }
}

function imposeStandardDateTypeInSystemHeader(document, oldDocument){
    if(document && document.systemHeader){

        var created = document.systemHeader.createdDate;
        if (created != null) {
            document.systemHeader.createdDate = new Date(created);

            if (oldDocument && oldDocument.systemHeader) {
                //compare date regardless of types i.e. string, date
                if (JSON.stringify(new Date(created)) === JSON.stringify(new Date(oldDocument.systemHeader.createdDate))) {
                    document.systemHeader.createdDate = new Date();
                }
            }
        }

        var serverCreatedDate = document.systemHeader.serverCreatedDate;
        if (serverCreatedDate != null) {
            document.systemHeader.serverCreatedDate = new Date(serverCreatedDate);
        }

        var serverUpdatedDate = document.systemHeader.serverUpdatedDate;
        if (serverUpdatedDate != null) {
            document.systemHeader.serverUpdatedDate = new Date(serverUpdatedDate);
        }

        const documentCreatedDate = document.systemHeader.documentCreatedDate;
        if (documentCreatedDate != null) {
          document.systemHeader.documentCreatedDate = new Date(documentCreatedDate);
        }
    }
}

const setDefaultValues = (document, template) => {
    if (template && template.components) {
        for (let component of template.components) {
            let value = document[component.name];
            if (UtilType.hasValue(component.defaultValue) && !UtilType.hasValue(value)) {
                document[component.name] = component.defaultValue;
            }
        }
    }

};

module.exports = {
    writeSystemHeader,
    imposeStandardDateTypeInSystemHeader,
    setDefaultValues,
    applySystemType
};
